Emma
Emma

Reputation: 134

how to update django cached_property

I would like to use @cached_property on model property to avoid too much db access.

class AttrGroup(models.Model):
    ...

    @cached_property
    def options(self):
        options = AttributeOption.objects.filter(group_id=self.id)
        return options
    ...

This works fine.

i want to use the following function to update the value of options.But how should i do it? for property decorator, there is setter for it.

def _set_options(self, value):
    for option in value:
        AttributeOption.objects.create(group_id=self.id, option=option.get('option'))

Upvotes: 10

Views: 8941

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Django's cached_property object replaces itself with the result of the decorated function call on the first call, so you cannot invalidate the cache.

EDIT : Stupid me - of course you can, you just have to del self.__dict__['options'] as answered by Albar - since the result is stored on the instance, removing it will make the class level cached_property attribute available again.

If you want something more 'reusable' you can have a look here : Storing calculated values in an object

Upvotes: 7

albar
albar

Reputation: 3100

You can invalidate the cached_property by deleting it:

del self.options

See here.

Upvotes: 17

Related Questions