M
M
maxclax2017-08-26 20:34:40
Django
maxclax, 2017-08-26 20:34:40

How does @cached_property work in django?

I can't understand how @cached_property works in the model. It is necessary to display the count of records. I do it with the following method:

class Categorie(MPTTModel):
    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.name

    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
    name = models.CharField(unique=True, max_length=60)
    slug = models.SlugField(unique=True, max_length=80, default='')
    created_at = models.DateField(auto_now_add=True)

    class MPTTMeta:
        order_insertion_by = ['name']

    @cached_property
    def sites(self):
        return self.site_set.count()

But with every request to sites, there is a request to the database. In my understanding, it should work according to the following scheme: the first request to the database and all subsequent requests from the cache. After del sites again query the database. Help understand

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Astrohas, 2017-08-26
@maxclax

You misunderstood cached _property, it is needed for lazy properties that will only be evaluated when called. There is an article on habr https://habrahabr.ru/post/159099/
And yes, this is not caching, but just lazy_load

A
Artem Klimenko, 2017-08-27
@aklim007

If the project is already using redis, then cacheops is a good solution . can be configured to cache only count queries of a specific model.
It goes without saying that you should use it with caution, and only where you encounter loads, you should not cache everything in a row.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question