Evgenii Legotckoi
Evgenii LegotckoiOct. 16, 2022, 2: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.


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.


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.

    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",


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.


You can use this decorator by following way.

from django_model_cached_property import model_cached_property

class Article(models.Model):

    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):

    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 .


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):

    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


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.


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!

  • Oct. 17, 2022, 6:32 a.m.

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

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

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


Only authorized users can post comments.
Please, Log in or Sign up

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

  • Result:50points,
  • Rating points-4

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

  • Result:73points,
  • Rating points1

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Last comments
Алексей НиколаевMarch 26, 2023, 9:10 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
Алексей НиколаевMarch 26, 2023, 9:04 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProjectMarch 24, 2023, 2:35 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 10:09 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
NSProjectMarch 24, 2023, 9:15 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Хорошая статья. И тут я подумал что на её основе можно отлично сформировать "хлебные крошки". Самое простое распарсить адрес. Так и поступил бы но лень
Now discuss on the forum
PisychMarch 29, 2023, 5:35 a.m.
Как подсчитать количество по условию? большое спасибо. завтра проверю. сейчас уже нет возможности:(
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
Виталий АнисимовJan. 29, 2023, 3:17 p.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.
PisychMarch 16, 2023, 12:23 a.m.
Как записать значение даты в Input date? Уппс! нашел ошибку. Тема закрыта
Evgenii Legotckoi
Evgenii LegotckoiMarch 15, 2023, 5:08 a.m.
Почему не работает редирект? Добрый день! Через Ajax редирект и не будет работать. Вам нужно вернуть JsonResponse и обработать его в на клиентской стороне в скрипте вызов Ajax. То есть вызвать редирект в этой фун…

Follow us in social networks