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
L
  • Leo
  • Sept. 26, 2023, 11:43 a.m.

C++ - Test 002. Constants

  • Result:41points,
  • Rating points-8
L
  • Leo
  • Sept. 26, 2023, 11:32 a.m.

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

  • Result:93points,
  • Rating points8
Last comments
IscanderChe
IscanderCheSept. 13, 2023, 9:11 a.m.
QScintilla C++ example По горячим следам (с другого форума вопрос задали, пришлось в памяти освежить всё) решил дополнить. Качаем исходники с https://riverbankcomputing.com/software/qscintilla/downlo…
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 7:18 a.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Разве могут взаимодействовать объекты из разных нитей как-то, кроме как через сигнал-слоты?" Могут. Выполняя оператор new , Вы выделяете под объект память в куче (heap), …
AC
Andrei CherniaevSept. 5, 2023, 3:37 a.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Я поясню свой вопрос. Выше я писал "Почему же в методе MainWindow::on_write_1_clicked() Можно обращаться к методам exampleObject_1? Разве могут взаимодействовать объекты из разных…
n
nvnAug. 31, 2023, 9:47 a.m.
QML - Lesson 004. Signals and Slots in Qt QML Здравствуйте! Прекрасный сайт, отличные статьи. Не хватает только готовых проектов для скачивания. Многих комментариев типа appCore != AppCore просто бы не было )))
NSProject
NSProjectAug. 24, 2023, 1:40 p.m.
Django - Tutorial 023. Like Dislike system using GenericForeignKey Ваша ошибка связана с gettext from django.utils.translation import gettext_lazy as _ Поле должно выглядеть так vote = models.SmallIntegerField(verbose_name=_("Голос"), choices=VOTES) …
Now discuss on the forum
IscanderChe
IscanderCheSept. 17, 2023, 9:24 a.m.
Интернационализация строк в QMessageBox Странная картина... Сделал минимально работающий пример - всё работает. Попробую на другой операционке. Может, дело в этом.
NSProject
NSProjectSept. 17, 2023, 8:49 a.m.
Помогите добавить Ajax в проект В принципе ничего сложного с отправкой на сервер нет. Всё что ты хочешь отобразить на странице передаётся в шаблон и рендерится. Ты просто создаёшь файл forms.py в нём описываешь свою форму и в …
BlinCT
BlinCTSept. 15, 2023, 12:35 p.m.
Размеры полей в TreeView Всем привет. Пытаюсь сделать дерево вот такого вида Пытаюсь организовать делегат для каждой строки в дереве. ТО есть отступ какого то размера и если при открытии есть под…
IscanderChe
IscanderCheSept. 8, 2023, 12:07 p.m.
Кастомная QAbstractListModel и цвет фона, цвет текста и шрифт Похоже надо не абстрактный , а "реальный" типа QSqlTableModel Да, но не совсем. Решилось с помощью стайлшитов и setFont. Спасибо за отлик!
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 6:35 a.m.
Вопрос: Нужно ли в деструкторе удалять динамически созданные QT-объекты. Напр: Зависит от того, как эти объекты были созданы. Если вы передаёте указатель на parent объект, то не нужно, Ядро Qt само разрулит удаление, если нет, то нужно удалять вручную, иначе будет ут…

Follow us in social networks