Nurzhan Nogerbek
Nurzhan Nogerbek

Reputation: 5246

How combine (merge) several number of querysets?

Can someone say how to combine (merge) several number of querysets. The number of querysets are not fixed. I tried next code but it didnt work as I expected. How to fix this problem?

first_list = []
for id in ids:
   products = Product.objects.filter(company=id)
   first_list.append(products)

final_list = list(chain(first_list))

This code return:

[<QuerySet [<1>, <2>]>, <QuerySet [<3>, <4>]>, <QuerySet [<5>, <6>]>]

I need:

[<QuerySet [<1>, <2>, <3>, <4>, <5>, <6>]>,]

Upvotes: 0

Views: 131

Answers (1)

Sayse
Sayse

Reputation: 43320

It appears as though you are just trying to get a list of products matching an existing list, so you can use __in, you can then make this a list too if you really need a list of querysets for some reason

 products = Product.objects.filter(company_id__in=ids)
 odd_list = [products]

The added advantage of this is that this performs a single query to your database instead of n queries, it also avoids the need to manually resolve the queryset so that it stays a lazy query and allows you to extend upon this query with further filters as necessary.

Upvotes: 1

Related Questions