0👍
✅
Assuming you have a view that populates a context variable named posts
with a queryset like Post.objects.all()
your template could look something like this simplified
{% for post in posts %}
{{ post.title }}
{{ post.category }}
{{ post.description }}
...
{% for image in post.images_set.all %}
{{ image.image.url }}
{% endfor %}
{% endfor %}
Every time you iterate over post.images_set.all
you will execute another query, you should use prefetch_related
so that you don’t perform a query each time and the data is cached
posts = Post.objects.prefetch_related('images_set')
1👍
You can use like this;
post = Post.objects.all().prefetch_related('images_set').get(pk=1)
images = post.images_set.all() # this will bring you all images related to
post
- [Answered ]-Django: Creating model instances with a random integer field value that average up to a specified number
- [Answered ]-"TemplateSyntaxError: Invalid filter:"; custom django template filter based on django docs broken, but template tags working
- [Answered ]-Django – separate authentication backend code from implementation
- [Answered ]-Django session id on android
Source:stackexchange.com