Search code examples
pythondjangodjango-models

How can I find the union of two Django querysets?


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 there any way to get a queryset, or just a list of objects, that’s the union of the querysets returned by each manager method?


Solution

  • This works and looks a bit cleaner:

    records = query1 | query2
    

    If you don't want duplicates, then you will need to append .distinct():

    records = (query1 | query2).distinct()