Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache a Django Model in Memory [duplicate]

i have a Model in my app, that is used so much in my application, some views made something like 100 queries in that Table, I already have a tons of optimisations to make a better use of this Model, but the great part of that amount is caused by the Django init method of other classes, for personal reasons... So actual i just put a global variable to store all the objects of that Model in there, so when i create or delete a one object from that Model I just reload that List... but i dont want to use cache machines like Memcached or Redis... i just want to store that QuerySet result in the Memory... And i want to still use the Managers in this cached Queryset.

Thanks in advance and sorry for my bad english.

like image 961
Luan Fonseca Avatar asked Oct 11 '13 22:10

Luan Fonseca


People also ask

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.

What type of caching mechanisms are Django supported?

Memcached. This is the most efficient caching system supported natively in Django. Memcached provides a fast interface for adding, retrieving, and deleting data from the cache. Here, all data are stored directly in memory instead of the database, which makes accessing the data faster.

Does Django automatically cache?

Local Memory Cache Unless we explicitly specify another caching method in our settings file, Django defaults to local memory caching. As its name implies, this method stores cached data in RAM on the machine where Django is running. Local memory caching is fast, responsive, and thread-safe.


2 Answers

You can use Django's provided caching.

This answer to a very similar question gets you on the right track.

like image 122
Joseph Avatar answered Oct 28 '22 19:10

Joseph


I would suggest implementing a custom model manager and a query set. A django cache backend doesn't have to be memcached or redis it can be localmemory also, although I would advise you to stand up a real cache backend. We mostly have been using https://github.com/jmoiron/johnny-cache for this purpose but found it is not compatible with django > 1.6 so we are switching over to https://github.com/vijaykatam/django-cache-manager

like image 20
Vijay Katam Avatar answered Oct 28 '22 19:10

Vijay Katam