Issue
I am currently using @cached_property
on a model class and I would like to delete it on save so that it can be repopulated on the next call. How do I do this?
Example:
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
Solution
Just del it as documentation says. It will lead to recalculation on next access.
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
For Python 3 it's the same use of del
. Below is an example of a try/except block.
try:
del obj.expensive_property
except AttributeError:
pass
Answered By - isobolev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.