0

Say you have the following method in a model:

    def get_images(self):
        return ReleaseImage.objects.filter(release=self.id)

And you call it from a template like so:

{% if release.get_images %}{{ MEDIA_URL }}{{ release.get_images.first }}{% endif %}

Does the database get queried twice, or is there some behind-the-scenes optimization that prevents this? It might be highly inefficient if not.

1 Answer 1

1

It queries twice here, yes. But we can optimize it with a {% with … %} template tag [Django-doc]:

{% with images=release.get_images %}
{% if images %}{{ MEDIA_URL }}{{ images.0 }}{% endif %}
{% endwith %}

As with (most) Django template tags, you can not add spaces around the equal sign (=).

Sign up to request clarification or add additional context in comments.

2 Comments

It's useful to add that the with tag does not accept spaces around the = , I struggled with that for a fair few minutes before I realized haha.
@bur: yes, although I think that is the case for (most) template tags. The Django template engine has some peculiarities regarding syntax. I actually don't really understand why they keep maintaining it, and just don't switch to Jinja, which is very similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.