Django将同一模型的两个查询集连接起来 [英] Django concatenate two querysets for same model
问题描述
我有一个个产品
的列表,每个产品都属于一个不同的 Distributor
。
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)
)
问题是我需要显示产品所属的表格到页面中名为 FirstDistributor 第一的特定 Distributor
。
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')
和
q2 = Product.objects.filter(product__id=product_id
).exclude(distributor__name='FirstDistributor')
谢谢!
推荐答案
您可以尝试就像这里一样:
You can try to do it like here:
https://stackoverflow.com/a / 2176471/4971083
这是在Django中按特定值对记录进行排序的解决方案。
您可以按distributor_name ='FirstDistributor'
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'])
这篇关于Django将同一模型的两个查询集连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!