3

I have a list of Products, each belonging to a different Distributor.

I need to display a form for each of those products and their corresponding distributor. I can do so with this code:

form_products = ProductFormSet(
    queryset = Product.objects.filter(product__id=product_id)
)

The problem is that I need to display the form with the product belonging to a particular Distributor named "FirstDistributor" first in the page.

I tried to do so with the following code using the | operator between the querysets:

form_products = ProductFormSet(
    queryset=(
        Product.objects.filter(
            product__id=product_id, 
            distributor__name='FirstDistributor') | 
        Product.objects.filter(
            product__id=product_id
        ).exclude(distributor__name='FirstDistributor')
    )
)

But the forms are still displayed in the same order. How can I concatenate those two querysets into one, while keeping the same order?

q1 = Product.objects.filter(product__id=product_id,
    distributor__name='FirstDistributor')

and

q2 = Product.objects.filter(product__id=product_id
    ).exclude(distributor__name='FirstDistributor')

Thanks!

Yeo
  • 11,416
  • 6
  • 63
  • 90
Michael
  • 1,557
  • 2
  • 18
  • 38
  • The Queryset class implements the iterator interface so it can be used as that, hence the **itertools.chain** method can be used to combine multiple querysets of the the same model together – Fanis Despoudis May 07 '15 at 18:32

2 Answers2

3

You can try to do it like here:

https://stackoverflow.com/a/2176471/4971083

It's the solution for ordering your records by specific value in Django. You could order your records by distributor_name = 'FirstDistributor'

p= Product.objects.filter(product__id=product_id).extra(
select={'is_top': " distributor__name='FirstDistributor'"})
p = p.extra(order_by = ['-is_top'])
Community
  • 1
  • 1
koala
  • 119
  • 8
1

You can use itertools to combine the two:

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

Source: https://stackoverflow.com/a/434755/3279262

Community
  • 1
  • 1
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25