我目前正在模型类上使用@cached_property
,我想在保存时将其删除,以便可以在下次调用时重新填充它。我该怎么做呢?
示例:
class Amodel():
#...model_fields....
@cached_property
def db_connection(self):
#get some thing in the db and cache here
instance = Amodel.objects.get(id=1)
variable = instance.db_connection
Amodel.objects.select_for_update().filter(id=1).update(#some variable)
#invalidate instance.db_connection
#new_variable = instance.db_connection
谢谢
最佳答案
只需将其删除为文档 says 。这将导致下次访问时重新计算。
class SomeClass(object):
@cached_property
def expensive_property(self):
return datetime.now()
obj = SomeClass()
print obj.expensive_property
print obj.expensive_property # outputs the same value as before
del obj.expensive_property
print obj.expensive_property # outputs new value
对于 Python 3,与 del
的用法相同。下面是 try/except block 的示例。
try:
del obj.expensive_property
except AttributeError:
pass
关于python - 如何在 django 中使 @cached_property 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489548/