Michael
Michael

Reputation: 1607

Django concatenate two querysets for same model

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!

Upvotes: 3

Views: 5291

Answers (2)

koala
koala

Reputation: 119

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'])

Upvotes: 3

Jorick Spitzen
Jorick Spitzen

Reputation: 1639

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

Upvotes: 1

Related Questions