如何选择相关的反向外键? [英] How to select_related on reverse foreign key?
问题描述
可能重复:
在Django中左侧外部反向select_相关?
A BlogPost
有许多评论
s。我想得到一个 BlogPost
及其所有评论的列表。
因此,我有
BlogPost.objects.filter(my_filter).select_related()
但外键位于评论
,而不是 BlogPost
,所以 select_related()
不预取任何注释。有没有办法让这个工作?
我无法反驳查询( Comment.objects ...
),因为那个 select_related()
的其他对象不能执行。我需要它两种方式工作。
为什么不会提取评论,然后使用重组模板标签以显示它们:
#使用BlogPost数据选择所有评论 - 一个查询
comments = Comment.objects.select_related('blog_post')。order_by(' - blog_post' ).all()
然后在模板中:
pre $
{%将blog_post的评论重新分组为帖子%}
{%for blog_post in posts%}
< p> Blog post { blog_post.title}}< / p>
< ul>
{%在blog_post.com中发表评论%}
...
{%endfor%}
< / ul>
< / p>
{%endfor%}
Possible Duplicate:
A left outer reverse select_related in Django?
A BlogPost
has many Comment
s. I want to get a list of BlogPost
s 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.
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 %}
这篇关于如何选择相关的反向外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!