Django - 查询集和一般 SQL 问题
首先,给定一个模型 Foo
且它的 m2m 指向 Bar
,以下查询如何工作(当没有任何内容是 NULL< /code> 本身(连接和第一部分被省略):
>> print Foo.objects.get(bar__isnull=True).query
...WHERE "barapp_bar"."id" IS NULL
空的东西让我对相关 m2m 的过滤感到困惑
其次,有没有办法让这个类似的查询在处理大量数据时更快。行数:
Foo.objects.get(bar__in=[bar1, bar2, bar3, bar4])
Firstly, given a model Foo
and it's m2m pointing to Bar
, how does the following query work (when nothing really is NULL
per se (join and first part ommited):
>> print Foo.objects.get(bar__isnull=True).query
...WHERE "barapp_bar"."id" IS NULL
The null stuff throws me off with regards to filtering by related m2m.
Secondly, is there a way to make this similar query faster when dealing with lots of rows:
Foo.objects.get(bar__in=[bar1, bar2, bar3, bar4])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
省略的连接很重要。如果您查看完整的查询,您将看到 Django 执行两个左外连接< /a> 从
foo
表到连接表foo_bar
和bar
表。考虑两个
foos
和两个bars
。令foo_1
与bar_1
和bar_2
相关,并且foo_2
不与任何bars.
下面的查询有两个左外连接,每个
foo
至少包含一次,并且 NULL 将出现在foo_2
的 bar 列中,该列与任何bars 都不相关
。Foo.objects.get(bar__isnull=True)
的查询与此类似,但它不会从 bar 表中选择任何内容,而是根据bar.id
进行过滤> 是NULL
,因为我们只想要与任何bars
无关的foos
。The ommitted joins are important. If you look at the full query, you will see that Django does two Left Outer Joins from the
foo
table to the joining tablefoo_bar
and to thebar
table.Consider two
foos
and twobars
. Letfoo_1
be related tobar_1
andbar_2
, andfoo_2
not be related to anybars
.The query below with two left outer joins with include every
foo
at least once, and NULL will appear in the bar column forfoo_2
which is not related to anybars
.The query for
Foo.objects.get(bar__isnull=True)
is similar to this, but it doesn't select anything from the bar table, and it filter onbar.id
isNULL
, because we only want thefoos
which are not related to anybars
.