如何更新django cached_property

Emm*_*mma 5 python django

我想在模型属性上使用@cached_property以避免过多的数据库访问.

class AttrGroup(models.Model):
    ...

    @cached_property
    def options(self):
        options = AttributeOption.objects.filter(group_id=self.id)
        return options
    ...
Run Code Online (Sandbox Code Playgroud)

这很好用.

我想使用以下函数来更新options的值.但我该怎么做呢?对于属性装饰器,它有一个setter.

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

bru*_*ers 7

Django 的cached_property对象在第一次调用时用装饰函数调用的结果替换自身,因此您不能使缓存无效。

编辑:愚蠢的我 - 当然你可以,你只需要del self.__dict__['options']按照 Albar 的回答 - 因为结果存储在实例中,删除它会使类级别cached_property属性再次可用。

如果你想要更“可重用”的东西,你可以看看这里:在对象中存储计算值


alb*_*bar 5

您可以cached_property通过删除使其无效:

del self.options
Run Code Online (Sandbox Code Playgroud)

这里

  • 最好使用del self .__ dict __ ['options']`-这样会使事情变得更清楚。 (2认同)
  • 请记住检查“hasattr”或“try... except”,因为它可能会引发异常。 (2认同)