Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple query sets in DJANGO [duplicate]

Tags:

python

django

I have to merge the querysets below in a single list:

result_list_1 = Col.objects.defer("tags").filter(producer__username__icontains=crit) 
result_list_2 = Col.objects.defer("tags").filter(name__icontains=crit)
result_list_3 = Col.objects.defer("tags").filter(description__icontains=crit)
result_list_4 = Col.objects.filter(tags__name__icontains=crit)
...

Each result_list contains items, which have a unique numeric id I can use to make sure there are no dups.

I can't use | while querying the DB or Q objects.

How do I merge the resulsets in one single list?

like image 524
Miki Avatar asked Mar 19 '23 14:03

Miki


1 Answers

What about a slight modification of itertools.chain that makes sure you don't get dupes:

def unique_chain(*iterables):
    known_ids = set()
    for it in iterables:
        for element in it:
            if element.id not in known_ids:
                known_ids.add(element.id)
                yield element

With that you can create your combined list:

combined_list = list(unique_chain(result_list_1, result_list_2, ... ))
like image 99
steffens21 Avatar answered Mar 31 '23 20:03

steffens21