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!

1
  • 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 Commented May 7, 2015 at 18:32

2 Answers 2

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'])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.