Reputation: 8608
Say I have a model with a cached property:
class MyModel(models.Model):
name = fields.Charfield()
@cached_property
def count_friends(self):
return self.friends_set.count()
Django states that:
The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned.
How does this means cached_property
works in the request/response cycle? For example, if I only use object.count_friends
in a template, will it be refreshed each time the view is called (assuming browser cache is cleared!)?
Have I understood this correctly? E.g. each time I make a call to the DB, I assume it's refreshed?
In what practical circumstances would it not be refreshed?
Upvotes: 1
Views: 832
Reputation: 169032
@cached_property
s are cached per-instance. The request-response cycle has no bearing on this (unless you stow away models as e.g. global variables which you shouldn't do or in the Django cache, ...)
def my_view(request):
m = MyModel.objects.get(id=42)
x = m.count_friends # causes a DB access
x = m.count_friends # does not cause a DB access
m = MyModel.objects.get(id=42)
x = m.count_friends # causes a DB access
x = m.count_friends # does not cause a DB access
Upvotes: 1