简体   繁体   中英

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 ?

Use the | operator. ie queryset = queryset1 | queryset2 | queryset3 queryset = queryset1 | queryset2 | queryset3 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 ie Tag.

What you want to do basically is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM