kriwil.com

Aldi on Random Stuff
2004 - 2024
Jun 12, 2014

django's cached_property

If you find yourself using @property a lot in your model and the property costs database queries, you might want to consider using cached_property instead.

For example:

:::python
...
from django.utils.functional import cached_property
...

class Book(models.Model):
    ...

    @cached_property
    def references(self):
        ...
        # more queries here
        return references

So instead re-query everytime you call the property, it'll use cache instead, as long as the instance still exists.