kriwil

aldiantoro nugroho on random stuff
Thu 12 June 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.

If you have any comment, mention me @kriwil.