Alb*_*ona 4 python django django-models django-queryset
我正在尝试将 2 个查询集连接在一起。现在,我正在使用|
运算符,但这样做不会起到“追加”的作用。
我当前的代码是:
df = RegForm((querysetA.all() | querysetB.all()).distinct())
Run Code Online (Sandbox Code Playgroud)
我需要将 querysetA 中的元素放在 querysetB 之前。甚至有可能在只保留查询的情况下完成任务吗?
annotate
这可以通过添加一个自定义字段来对查询集进行排序来解决,并union
像这样使用它:
from django.db.models import Value
a = querysetA.annotate(custom_order=Value(1))
b = querysetB.annotate(custom_order=Value(2))
a.union(b).order_by('custom_order')
Run Code Online (Sandbox Code Playgroud)
在django-3.2之前,您需要指定output_field
for Value
:
from django.db.models import IntegerField
a = querysetA.annotate(custom_order=Value(1, IntegerField()))
b = querysetB.annotate(custom_order=Value(2, IntegerField()))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1423 次 |
最近记录: |