Django concatenate two querysets for same model

你离开我真会死。 提交于 2019-12-20 02:41:39

问题


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:


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



回答2:


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



来源:https://stackoverflow.com/questions/30102848/django-concatenate-two-querysets-for-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!