simple way for QuerySet union and subtraction in django?

后端 未结 5 803
醉话见心
醉话见心 2021-02-07 02:15

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 the

5条回答
  •  爱一瞬间的悲伤
    2021-02-07 02:42

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

    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.
    

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

提交回复
热议问题