Django combine multiple QuerySets
Suppose that we have two different models.
class Author(models.Model):
name = models.CharField(max_length=50)
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
In certain circumstances, you might want to merge two querysets into one queryset. For example, you may want to combine Author.objects.all()
and Article.objects.all()
. You could accomplish this by pure python method itertools.chain
, or using Django's inbuilt queryset method union
. However, these are no more intuitive than combining two querysets directly.
We recommend to use the package django-querysetsequence
. To combine Author.objects.all()
and Article.objects.all()
, you just need to call QuerySetSequence
directly :
from queryset_sequence import QuerySetSequence
authors = Author.objects.all()
articles = Article.objects.all()
authors_articles = QuerySetSequence(authors, articles)
If you have multiple models A, B, C, D, E, F
, and have an array data
containing their querysets, e.g. A.objects.all(), B.objects.all()
, etc. To combine querysets in an array, you could make use of python's inbuilt method reduce
:
from functools import reduce
from queryset_sequence import QuerySetSequence
q = reduce(QuerySetSequence, data)
There is no comment, let's add the first one.