简体   繁体   English

如何更新django cached_property

[英]how to update django cached_property

I would like to use @cached_property on model property to avoid too much db access. 我想在模型属性上使用@cached_property以避免过多的数据库访问。

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? 我想使用以下函数来更新options的值。但我该怎么做呢? for property decorator, there is setter for it. 对于属性装饰器,它有一个setter。

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

You can invalidate the cached_property by deleting it: 您可以通过删除cached_property来使其无效:

del self.options

See here . 看到这里

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. Django的cached_property对象将替换为第一次调用时修饰函数调用的结果,因此您无法使缓存无效。

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. 编辑:愚蠢我 - 当然你可以,你只需要del self.__dict__['options']由Albar回答 - 因为结果存储在实例上,删除它将使类级别cached_property属性再次可用。

If you want something more 'reusable' you can have a look here : Storing calculated values in an object 如果您想要更“可重复使用”的东西,可以在这里查看: 在对象中存储计算值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM