Django 中 QuerySet 联合和减法的简单方法?
考虑同一类的两个 QuerySet 对象。 有没有一种简单的方法可以通过计算并集将它们统一为一个查询集? 另外,有没有简单的方法来减去它们?从其中一个集合中删除两个集合中出现的所有元素?
Consider two QuerySet objects of the same class.
Is there a simple way to unify them into a single QuerySet by calculating the union?
Also, is there a simple way to subtract them? Removing all elements that appear in both sets from one of the sets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 Django 1.11 开始,查询集具有
union()
,intersection()
和difference()
方法。也可以使用
&
和 < code>| 带有 QuerySet 的中缀运算符(我在文档中找不到对此的引用,所以我猜union()
和intersection() 是组合两个查询集的首选方式。
您还可以使用
Q()
对象,类似于 QuerySets 实现|
和&
,以及反转前缀运算符~
都没有实现异或/对称差中缀运算符
^
。Since Django 1.11, QuerySets have
union()
,intersection()
anddifference()
methods.It's also possible to use
&
and|
infix operators with QuerySets (I could not find a reference to this in the docs, so I guessunion()
andintersection()
is the preferred way to combine two querysets.You can also use
Q()
objects which like QuerySets implement|
and&
, and additionally the invert prefix operator~
.Neither class implement the xor / symmetric difference infix operator
^
.使用相同模型从另一个 QuerySet 中减去一个 QuerySet。
这有效 - 但可能很慢
阅读 django 文档中的性能注意事项:
https://docs。 djangoproject.com/en/dev/ref/models/querysets/#in
Subtract a QuerySet from another QuerySet using the same model.
This works - but is probably slowly
Read the performance considerations in django documentation:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#in
回到 django 的文档,您可以:
这作为逻辑 OR 工作,实际上是加法无重复。这回答了加法方面,并且据我所知根本没有击中数据库!
这相当于逻辑“与”。
仍然缺少如何减去查询集。我很难相信社区没有优雅地处理这个问题......
Going back to django's documentation, you can:
This works as a logical OR which is actually addition without duplicates. This answers the addition aspect and AFAIK does not hit the db at all!
This works as a logical AND.
Still missing how to subtract QuerySets. It's hard for me to believe this has not been dealt with elegantly by the community...
您可以使用
Q
对象。语法可能是这样的:
您可能可以根据实际需要进行优化并降低数据库命中数(现在是 3),但这应该可以帮助您入门。
You can use the
Q
object.The syntax could be something like this:
You probably can optimize based on your actual needs and get the amount of db hits down (right now it's 3), but this should get you started.
我认为对于这样的操作,你需要对其进行评估。因此,您可以对它们调用
list()
并使用常见的 Python 列表操作来处理它们!I think for operations as this you need to evalute them. So you can call
list()
on them and work on them with the common python list operations!