How to select_related on reverse foreign key? [duplicate]

余生颓废 提交于 2019-12-05 00:24:59

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 %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!