python - 如何在 django 中使 @cached_property 无效

标签 python django django-models django-views

我目前正在模型类上使用@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/

相关文章:

python - 在回调 Dash 中使用 2 个输入动态更新下拉选项

python - 将代理图例句柄添加到现有图例

Django——在管理界面中过滤外键下拉菜单

python - 在 Django 模型中的一个变量中存储多个信息

php - 我如何在 django 中使用现有数据库(mysql)?

python - 以不同于 Python 的用户身份运行进程

python - 我可以从 print 语句调用 Python 中的函数吗?

python - 类型错误 : issubclass() arg 1 must be a class in Django tests

python : selenium click on submit no redirect

python - django 中的多语言 url 如何工作?