我目前正在使用@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
Thanks
只需将其删除为文档即可says https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.functional.cached_property。这将导致下次访问时重新计算。
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 块的示例。
try:
del obj.expensive_property
except AttributeError:
pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)