Django 中的左外反向 select_lated?

发布于 2024-09-03 20:48:26 字数 450 浏览 8 评论 0原文

想象一下以下模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

地狱即天堂 2024-09-10 20:48:26

从 Django 1.4 prefetch_lated 开始,可以满足您的需求。

Parent.objects.prefetch_related('child_set')

相关(!)django 文档: https://docs.djangoproject .com/en/dev/ref/models/querysets/#prefetch-lated

Starting from Django 1.4 prefetch_related does what you want.

Parent.objects.prefetch_related('child_set')

Related(!) django docs : https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related.

兮子 2024-09-10 20:48:26

在这种情况下,我认为最好的办法是列出子级,然后从它们中获取父级,如下所示:

children = Child.objects.filter(...).select_related('parent').order_by('parent')

然后在模板中,可能使用regroup(注意order_by< /代码> 上面):

{% regroup children by parent as parents %}
<ul>
{% for parent in parents %}
    <li>{{ parent.grouper }}
    <ul>
    {% for child in parents.list %}
    ...
    {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

In this case, I think the best thing to do is list the children, then get the parent from them, like this:

children = Child.objects.filter(...).select_related('parent').order_by('parent')

Then in the template, possibly use a regroup (note the order_by above):

{% regroup children by parent as parents %}
<ul>
{% for parent in parents %}
    <li>{{ parent.grouper }}
    <ul>
    {% for child in parents.list %}
    ...
    {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
感情废物 2024-09-10 20:48:26

我认为您正在寻找 select_lated()

I think you are looking for select_related()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文