This tip is particularly useful when you want to merge two or more querysets into a single queryset without losing
the capabilities of performing filter
, count
, distinct
, etc. operations.
Consider the following models:
Let’s say you want to display all the stories published in a specific Medium
together with stories written by a
User
using the Category
django. Note that this User
might have published stories in different Medium
:
At this point we have two different querysets, one containing all the stories from a medium and other containing all the stories from a user using the django category.
The querysets can be merged like in the example below, using the |
operator:
And you still can perform queryset operations:
It’s important to note that the merge/combine operator |
only works on querysets from the same model and before the
slicing it.