How can I find the union of two Django querysets?

前端 未结 3 652
清歌不尽
清歌不尽 2020-11-29 01:58

I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object.

Is ther

3条回答
  •  迷失自我
    2020-11-29 02:48

    Starting from version 1.11, django querysets have a builtin union method.

    q = q1.union(q2) #q will contain all unique records of q1 + q2
    q = q1.union(q2, all=True) #q will contain all records of q1 + q2 including duplicates
    q = q1.union(q2,q3) # more than 2 queryset union
    

    See my blog post on this for more examples.

提交回复
热议问题