0

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>]>,]
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • 2
    Are you looking for `Product.objects.filter(company_id__in=ids)`? – Sayse May 10 '17 at 12:27
  • I dont understand you. What you mean? – Nurzhan Nogerbek May 10 '17 at 12:30
  • I dont understand what you're actually trying to do, I presume you want to get all products with a company in the set of id's you already have (also assuming company is a FK) – Sayse May 10 '17 at 12:31
  • 1
    Here the official doc for the `in` operator https://docs.djangoproject.com/en/1.11/ref/models/querysets/#in `Entry.objects.filter(id__in=[1, 3, 4])` whitout using the `for` statement – e.arbitrio May 10 '17 at 12:31
  • 1
    @Sayse Thanks! That's what I was looking for! Can you answer one more time not as comment. I can mark your answer. – Nurzhan Nogerbek May 10 '17 at 12:35

1 Answers1

1

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.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 1
    Good answer but I wish you had added the big about why this is so much more peformant than the OP's original attempt too – e4c5 May 10 '17 at 13:04
  • @e4c5 - Good point, I've added an additional sentence to expand upon its capabilities. Thanks – Sayse May 10 '17 at 13:35