[ACCEPTED]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)-orm

Accepted answer
Score: 50

The approach you are doing now will be heavily inefficient, because 13 it will result in an 1+N number of queries. That 12 is, 1 for the query of all your Newsletters, and 11 then 1 for every single time you evaluate 10 those n.article_set.all() results. So if you have 100 Newletter 9 objects in that first query, you will be 8 doing 101 queries.

This is an excellent reason 7 to use prefetch_related. It will only result in 2 queries. One 6 to get the Newsletters, and 1 to batch get 5 the related Articles. Though you are still 4 perfectly able to keep doing the zip to organize 3 them, they will already be cached, so really 2 you can just pass the query directly to 1 the template and loop on that. :


newsletters = Newsletter.objects.prefetch_related('article_set').all()\
                    .order_by('-year', '-number')

return render_to_response('newsletter/newsletter_list.html',
                          {'newsletter_list': newsletters})


{% block content %}
  {% for newsletter in newsletter_list %}
    <h2>{{ newsletter.label }}</h2>
    <p>Volume {{ newsletter.volume }}, Number {{ newsletter.number }}</p>
    <p>{{ newsletter.article }}</p>
    {% for a in newsletter.article_set.all %}
      <li>{{ a.title }}</li>
    {% endfor %}
  {% endfor %}
{% endblock %}

More Related questions