3👍
✅
Here’s how you write a caching property without explicitly setting the cache to None
in the __init__
method:
def _get_image(self):
if not hasattr(self, '_image'):
self._image = Media.objects.get_for_object(self)
return self._image
image = property(_get_image)
or in more modern syntax
@property
def image(self):
if not hasattr(self, '_image'):
self._image = Media.objects.get_for_object(self)
return self._image
6👍
“or something”?
Why should it store the results? You’ve explicitly written the _get_image
function so that it queries the database each time. If you want it to store the results, you need to tell it to do it.
Probably the simplest way would be to just get it once in the template:
{% with entry.image as images %}
{% if images %}
<h2>Current image:</h2>
{% for m in images %}
{{ m }}
{% endfor %}
{% endif %}
{% endwith %}
Source:stackexchange.com