2

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 ?

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

K but i am getting the querysets from the for loop as above, so how to merge them using | or & from for loop ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.