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
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

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

  • Result:53points,
  • Rating points-4
АА

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

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 2:43 a.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, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
K
KeithfapOct. 13, 2024, 4:24 p.m.
добавить qlineseries в функции North Symbol by Bubnov Ltd https://seven-elephants.com/en/categories/penthouse/ Искеле – жемчужина острова! Все факторы говорят про большой инвестиционный потенциал данного района как для …
JW
Jhon WickOct. 1, 2024, 10:52 p.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 4:09 p.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 11:15 a.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks