Shiva Krishna Bavandla
Shiva Krishna Bavandla

Reputation: 26648

How to combine/merge more than one queryset in to single queryset django

I have a queryset as below

entries = [<Entry: Entry got issues>, <Entry: Entry Latest entry>, <Entry: Entry now tested>]

Each object in the above queryset entries will have a queryset as below

for entry in entries:
    print entry.tags.all()

Result

[<Tag: published>, <Tag: tags>, <Tag: needs>, <Tag: be>, <Tag: issues>, <Tag: to>]
[<Tag: abcd>]
[<Tag: abcd>, <Tag: nothing>]

so i want to merge the above three querysets in the result on to a single queryset as below

[<Tag: published>, <Tag: tags>, <Tag: needs>, <Tag: be>, <Tag: issues>, <Tag: to>]
 <Tag: abcd>, <Tag: abcd>, <Tag: nothing> ]

So how to merge/combine three querysets in to one above in django ?

Upvotes: 2

Views: 647

Answers (1)

Aleister
Aleister

Reputation: 153

Use the | operator. i.e queryset = queryset1 | queryset2 | queryset3 But you can also use the & operator to find intersection. You have to make sure that all the querysets return are of the same objects i.e Tag.

What you want to do basically is

queryset = entries[0].tags.all()
for entry in entries[1:]:
    queryset = queryset | entry.tags.all()

Upvotes: 3

Related Questions