How to select_related on reverse foreign key? [duplicate]

本秂侑毒 提交于 2019-12-22 03:09:52

问题


Possible Duplicate:
A left outer reverse select_related in Django?

A BlogPost has many Comments. I want to get a list of BlogPosts and all their comments.

Thus, I have

BlogPost.objects.filter(my_filter).select_related()

But the ForeignKey is on the Comment, not the BlogPost, so the select_related() doesn't prefetch any comments. Is there a way to get this to work?

I can't reverse the query (Comment.objects...) because then the other objects that the select_related() does fetch wouldn't work. I need it to work both ways.


回答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 %}


来源:https://stackoverflow.com/questions/6887171/how-to-select-related-on-reverse-foreign-key

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