[Answered ]-Query Multiple Tables in Django and geta consolidated result

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

Leave a comment