Django 中的左外反向 select_lated?
想象一下以下模型:
class Parent(Model):
...
class Child(Model)
father = ForeignKey(Parent)
...
有些父母有孩子,有些则没有(他们不是真正意义上的父母,只是一个虚构的名字)。
我想做以下查询:我想列出所有父母,如果他们有孩子,也把孩子带给我。这相当于子表的左外连接,即:
select * from app_parent left join app_child on child_father_id=parent_id
这样,当我在模板中调用 Parent.child_set 时,我不会无数次访问数据库。有办法做到这一点吗? 谢谢
Imagine the following model:
class Parent(Model):
...
class Child(Model)
father = ForeignKey(Parent)
...
Some parents have children, others do not (they're not parents in the real meaning, it's just a fictional name).
I would like to make the following query: I want to list all the Parents, and if they have children, bring me the children too. That would be the equivalent of a left outer join to Child table, that is:
select * from app_parent left join app_child on child_father_id=parent_id
This way, when I invoke Parent.child_set in my template, I won't hit the database a gazillion times. Is there a way to do that?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Django 1.4
prefetch_lated
开始,可以满足您的需求。相关(!)django 文档: https://docs.djangoproject .com/en/dev/ref/models/querysets/#prefetch-lated。
Starting from Django 1.4
prefetch_related
does what you want.Related(!) django docs : https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related.
在这种情况下,我认为最好的办法是列出子级,然后从它们中获取父级,如下所示:
然后在模板中,可能使用
regroup
(注意order_by< /代码> 上面):
In this case, I think the best thing to do is list the children, then get the parent from them, like this:
Then in the template, possibly use a
regroup
(note theorder_by
above):我认为您正在寻找 select_lated()
I think you are looking for select_related()