Django: Invalidate Cached Property

Sometimes we create property within our model for utility helper. And django provide decorator “@cached_property” for caching heavy computation within our property.

class Member(models.Model):
    # field definitions.

    @cached_property
    def score(self):
        return # heavy computation/query

I got a problem once testing my model and the property is still load the cached version of data instead of the latest. Here is how to invalidate cached property.

del member.score          # Invalidate cache.
delattr(member, 'score')  # Alternative to invalidate cache.

Reference: https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.functional.cached_property

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s