Evgenii Legotckoi
Evgenii LegotckoiOct. 16, 2022, 3:58 p.m.

django_model_cached_property - Caching property for individual model objects in Django

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

NSProject
  • Oct. 17, 2022, 7:32 a.m.

О хорошая статья. Для какой ветки Django будет работать эта батарейка?

Evgenii Legotckoi
  • Oct. 17, 2022, 7:37 a.m.
  • (edited)

Я тестировал только на Django 4, но сам код не менялся пожалуй с версии Django 2, так что предполагаю, что должно работать во всех версиях, но если протестируете на более ранних версиях, и будет нормально работать, то дайте фидбек. Спасибо.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks