Q&A
Ask and answer questions to make information more available to wider audiences.
Brantley Galeana @galeanabrantley   04, May 2023 12:00 AM
multiple QuerySets in a View
How to combine multiple QuerySets in a View?
answers 1
 
Answer 1
Katie Morriss @morrisskatie   05, May 2023 07:56 PM
QuerySets can be combined into another QuerySet, and they do not have to be from the same model.

To merge QuerySets from the same model, use the Python union operator.

The union operator can be used to combine two or more QuerySets with the following syntax: 

model_combination = model_set1 | model_set2 | model_set3 

Additionally, you can concatenate two or more QuerySets from other models by using the chain() method from the Itertools package. 

from itertools import chain

model_combination = list(chain(model_set1, model_set2)) 

As an alternative, you can merge two or more QuerySets from other models using union(), passing all=TRUE to allow for duplication.

model_combination = model_set1.union(model_set2, all=TRUE)