simple way for QuerySet union and subtraction in django?

后端 未结 5 793
醉话见心
醉话见心 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:21

    You can use the Q object.

    The syntax could be something like this:

    added_query_set = YourModel.objects.\
             filter(Q(id__in=old_query_set_1)|Q(id__in=old_query_set_2))
    

    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.

提交回复
热议问题