Introducing the release of the stable battery django_model_cached_property for caching property for individual model objects in Django.
I already said that evileg_core contains similar functionality, but now I decided to bring this caching into a separate package. This is due to the fact that I do not have time to maintain such a large package, and I use separate small functionality in my other projects. Therefore, it seemed logical to me to break a large project into independent projects, so that it would be easier to support at least the most requested functionality, at least within the framework of my own projects. I also hope that this package will be very useful for other developers.
Purpose
The package is used to cache the result of model object methods for a period longer than the existence of the object instance while the user's request is being processed. This is necessary in order to cache heavy database queries, the results of which should theoretically not change quite often, but at the same time calling them every time the user requests can greatly reduce the speed of the user's work with the Django application. This can be useful, for example, for information about whether the user liked an object, as well as the number of likes, in the event that Generic relationships in the database are used. Unfortunately, such connections do not work as fast as we would like. Therefore, proper caching can greatly speed up the site.
And now I will tell you how to use this functionality.
Install
pip install -U django-model-cached-property
Install and configure requirements
Install redis for caching.
sudo apt install redis-server
Configure setup.py of your django project.
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
Using
Package contains two functions:
- model_cached_property - it is decorator for class methods, which will cache results of property call for separate records.
- invalidate_model_cached_property - it is function for invalidation of method on the model record property.
model_cached_property
You can use this decorator by following way.
from django_model_cached_property import model_cached_property class Article(models.Model): @model_cached_property def comments_count(self): return self.comments.count()
It means you cache comments count for each record of article in your Django project.
You can set up cache timeout 3000 second by following way.
class Article(models.Model): @model_cached_property(timeout=3000) def comments_count(self): return self.comments.count()
By default, caching timeout is 60 second, by you can set up it globally in settings.py .
MODEL_CACHED_PROPERTY_TIMEOUT = 300000
Additionally, you can use caching of model property with input arguments.
And in this case caching will be evaluated for all input sets of arguments.
For example caching by authenticated user.
class Article(models.Model): @model_cached_property def __user_in_bookmarks(self, user): return self.bookmarks.filter(user=user).exists() def user_in_bookmarks(self, user): return self.__user_in_bookmarks(user) if user.is_authenticated else False
invalidate_model_cached_property
This function invalidate all cache keys on the property for one model record in database.
For example
article = get_object_or_404(Article, pk=12) invalidate_model_cached_property(article, article.comments_count)
In this case you invalidate all cached keys for article with primary key 2.
WARNING - Limitation
Limitation of this caching functionality consists in the fact that you can use it with unique input arguments only.
It means, that will not work with AnonymousUser object, because of in each request information about AnonymousUser object will be different, although it will be called by same user.
Therefore, use it on unique information only.
Conclusion
Dear users of the EVILEG website, if it's not difficult for you, please rate the project repository on GitHub with an asterisk
О хорошая статья. Для какой ветки Django будет работать эта батарейка?
Я тестировал только на Django 4, но сам код не менялся пожалуй с версии Django 2, так что предполагаю, что должно работать во всех версиях, но если протестируете на более ранних версиях, и будет нормально работать, то дайте фидбек. Спасибо.