Django中QuerySet联合和减法的简单方法? [英] simple way for QuerySet union and subtraction in django?

查看:499
本文介绍了Django中QuerySet联合和减法的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑同一类的两个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?

推荐答案

自Django 1.11开始,QuerySet具有 union() intersection() difference() 方法。

Since Django 1.11, QuerySets have union(), intersection() and difference() methods.

也可以使用 & | 运算符(我无法在docs,所以我想 union() intersection()是组合两个查询集的首选方法。

It's also possible to use & and | operators with QuerySets (I could not find a reference to this in the docs, so I guess union() and intersection() is the preferred way to combine two querysets.

qs3 = qs1.union(qs2)         # or qs3 = qs1 | qs2
qs3 = qs1.intersection(qs2)  # or qs3 = qs1 & qs2
qs3 = qs1.difference(qs2)    # the ^ operator is not implemented.

您还可以使用 Q() 对象,类似于QuerySets实现 | & ,以及反转运算符

You can also use Q() objects which like QuerySets implement | and &, and additionally the inversion operator ~

这篇关于Django中QuerySet联合和减法的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆