How to merge multiple queryset in a Django

0 votes
113 views
asked Mar 6 by katib (112 points)
edited Mar 7 by katib

I have three different queryset from same django model Post

q1 = Post.object.filter(criteria_1)

q2 = Post.object.filter(criteria_2)

how can i merge the result of these two querysets in one ?

something like result = q1+q2

3 Answers

0 votes
answered Mar 6 by katib (112 points)

One way of merging these query set is

result = Post.object.filter(Q(criteria_1) | Q(criteria_2))

or you can just do

result = q1 | q2

to merge your two or any query sets

0 votes
answered Mar 11 by anonymous

I have no idea what is your queryset filter criteria but this is how you merge multiple queryset for same model

q1 = Post.object.filter(author_id=55)
q2 = Post.object.filter(publisher_id=1095)

result = q1|q2

same as

result = Post.objects.filter(Q(author_id=55) | Q(publisher_id=1095))

which in sql equivalent of

WHERE author_id = '55' OR publisher_id = '1095'

Remember queryset are lazy, don't forget to check sql genereated using .query() to figure out what django ORM is doing.

0 votes
answered Mar 11 by anonymous

How about chain on queryset

posts = Post.objects.all()
comments = Comment.objects.all()
entries = list(chain(cars, trucks))

Welcome , qPocho is an online community for programmers share there knowledge.
...