[Fixed]-How to select_related on reverse foreign key?

-1👍

Why won’t you fetch the comments and then use regroup template tag to display them:

# Select all Comments with BlogPost data - one query
comments = Comment.objects.select_related('blog_post').order_by('-blog_post').all()

Then in template:

{% regroup comments by blog_post as posts %}
{% for blog_post in posts %}

    <p>Blog post {{ blog_post.title }}</p>
    <ul>
    {% for comment in blog_post.comments %}
    ...
    {% endfor %}
    </ul>
    </p>
{% endfor %}

Leave a comment