【问题标题】:how to update django cached_property如何更新 django cached_property
【发布时间】:2017-03-27 06:22:04
【问题描述】:

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

class AttrGroup(models.Model):
    ...

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

这很好用。

我想用下面的函数来更新options的值。但是我应该怎么做呢?对于属性装饰器,有它的设置器。

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

【问题讨论】:

  • 我刚刚找到另一个装饰器lru_cache,我的问题的另一个解决方案

标签: python django


【解决方案1】:

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

del self.options

here

【讨论】:

  • del self.__dict__['options'] 更好——它让事情更清晰。
  • 你误解了我的问题,但还是谢谢你。布鲁诺的回答是我需要的
  • 记得检查hasattrtry...except,因为它可能引发异常。
【解决方案2】:

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

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

如果你想要更“可重复使用”的东西,你可以看看这里:Storing calculated values in an object

【讨论】:

  • 谢谢,实际上你之前的回答解决了我的问题。如您所见,AttrGroup 类中的options 属性实际上是从表AttributeOption 中获得的。我的最终目的是在获取options时尽可能少地访问db(所以我使用cached_property而不是property装饰器,我也可以通过attrgroup.options = options修改AttributeOption(这是我需要的地方_set_options 方法),但cached_property 不支持setter。这是让我困惑的地方
猜你喜欢
  • 2014-06-22
  • 2015-09-22
  • 1970-01-01
  • 2020-05-24
  • 2016-09-25
  • 2015-05-15
  • 2020-11-27
  • 2013-01-31
  • 1970-01-01
相关资源
最近更新 更多