28
Another option may be to use:
class Meta:
managed = False
to prevent Django from creating a database table.
https://docs.djangoproject.com/en/2.2/ref/models/options/#managed
17
Just sounds like a regular Class
to me.
You can put it into models.py
if you like, just don’t subclass it on django.db.models.Model
. Or you can put it in any python file imported into the scope of whereever you want to use it.
Perhaps use the middleware to instantiate it when request comes in and discard when request is finished. One access strategy might be to attach it to the request object itself but ymmv.
- [Django]-Check for pending Django migrations
- [Django]-Using {% url ??? %} in django templates
- [Django]-Mysql error : ERROR 1018 (HY000): Can't read dir of '.' (errno: 13)
6
Unlike SQLAlchemy, django’s ORM does not support querying on the model without a database backend.
Your choices are limited to using a SQLite in-memory database, or to use third party applications like dqms which provide a pure in-memory backend for django’s ORM.
- [Django]-The view didn't return an HttpResponse object. It returned None instead
- [Django]-Django values_list vs values
- [Django]-Django model inheritance: create sub-instance of existing instance (downcast)?
2
So this is 11 years ago, but I ran into the exact same problem as the original poster and came up with a clever solution I thought I’d share:
models.py:
import requests
from collections import UserList
from django.core.cache import caches
from django.db import models
CACHE = caches["default"]
class MyTransientModelManager(models.Manager):
cache_key = "cached-transient-models"
cache_sentinel = object()
cache_timeout = 60 * 10
def get_queryset(self):
transient_models_data = CACHE.get(self.cache_key, self.cache_sentinel)
if transient_models_data is self.cache_sentinel:
response = requests.get("some/remote/api")
response.raise_for_status()
transient_models_data = response.json()
CACHE.set(self.cache_key, transient_models_data, self.cache_timeout)
return MyTransientModelQueryset([
MyTransientModel(**data)
for data in transient_models_data
])
class MyTransientModelQueryset(UserList):
# custom filters go here
pass
class MyTransientModel(models.Model):
class Meta:
managed = False
objects = MyTransientModelManager.from_queryset(MyTransientModelQuerySet)()
id = models.IntegerField(primary_key=True)
foo = models.CharField(max_length=255)
bar = models.TextField(null=True)
serializers.py:
from rest_framework import serializers
from my_app.models import MyTransientModel
class MyTransientModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyTransientModel
fields = ["id", "foo", "bar"]
views.py:
from rest_framework.exceptions import APIException
from rest_framework.generics import ListAPIView
from rest_framework.permissions import AllowAny
from my_app.models import MyTransientModel
from my_app.serializers import MyTransientModelSerializer
class MyTransientModelView(ListAPIView):
permission_classes = [AllowAny]
serializer_class = MyTransientModelSerializer
def get_queryset(self):
try:
queryset = MyTransientModel.objects.all()
return queryset
except Exception as e:
raise APIException(e) from e
- [Django]-How to upload multiple images to a blog post in django
- [Django]-Django: sqlite for dev, mysql for prod?
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-How to automate createsuperuser on django?
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-How to force migrations to a DB if some tables already exist in Django?
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
- [Django]-UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)
- [Django]-How to force migrations to a DB if some tables already exist in Django?
0
You need Caching, which will store your data in Memory and will be seperate application.
With Django, you can use various caching backend such as memcache, database-backend, redis etc.
Since you want some basic query and sorting capability, I would recommend Redis. Redis has high performance (not higher than memcache), supports datastructures (string/hash/lists/sets/sorted-set).
Redis will not replace the database, but will fit good as Key-Value Database Model, where you have to prepare the key to efficiently query the data, since Redis supports querying on keys only.
For example, user 'john.doe' data is: key1 = val1
The key would be - john.doe:data:key1
Now I can query all the data for for this user as - redis.keys("john.doe:data:*")
Redis Commands are available at http://redis.io/commands
Django Redis Cache Backend : https://github.com/sebleier/django-redis-cache/
- [Django]-How to return HTTP 400 response in Django?
- [Django]-How to dynamically compose an OR query filter in Django?
- [Django]-How to squash recent Django migrations?
0
Delete migration directory
If you delete the migrations directory of the app, django ignores creating migrations for this app. Migration related functionality like permissions are then not working anymore for the whole app.
This way you can create ModelForms, DRF Serializers or such from a Model that has not tables in database.
This is not a answer to the question but for the title. Often i stumbled upon this thread and maybe it can save someones time.
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-ImageField overwrite image file with same name
- [Django]-How to use django 3.0 ORM in a Jupyter Notebook without triggering the async context check?
-19
I make my bed to MongoDB or any other nosql; persisting and deleting data is incredibly fast, you can use django-norel(mongodb) for that.
- [Django]-Get object by field other than primary key
- [Django]-Django Rest Framework writable nested serializers
- [Django]-How to get the name of current app within a template?