Quantcast
Channel: How to combine multiple querysets in Django? - Stack Overflow
Viewing all articles
Browse latest Browse all 32

Answer by Udi for How can I combine two or more querysets in a Django view?

$
0
0

Related, for mixing querysets from the same model, or for similar fields from a few models, starting with Django 1.11 a QuerySet.union() method is also available:

union()

union(*other_qs, all=False)

New in Django 1.11. Uses SQL’s UNION operator to combine the results of two or more QuerySets. For example:

>>> qs1.union(qs2, qs3)

The UNION operator selects only distinct values by default. To allow duplicate values, use the all=Trueargument.

union(), intersection(), and difference() return model instances ofthe type of the first QuerySet even if the arguments are QuerySets ofother models. Passing different models works as long as the SELECTlist is the same in all QuerySets (at least the types, the names don’tmatter as long as the types in the same order).

In addition, only LIMIT, OFFSET, and ORDER BY (i.e. slicing andorder_by()) are allowed on the resulting QuerySet. Further, databasesplace restrictions on what operations are allowed in the combinedqueries. For example, most databases don’t allow LIMIT or OFFSET inthe combined queries.


Viewing all articles
Browse latest Browse all 32

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>