Django 在保持顺序的同时合并 QuerySet

Django merge QuerySet while keeping the order

我正在尝试将 2 个查询集连接在一起。现在,我正在使用 | 运算符,但这样做不会起到“追加”的作用。

我当前的代码是:

df = RegForm((querysetA.all() | querysetB.all()).distinct())

我需要 querysetA 中的元素位于 querysetB 之前。是否有可能在只保留查询的同时完成?

这可以通过使用 annotate to add custom field for ordering on the querysets, and use that in a union 解决:

a = querysetA.annotate(custom_order=Value(1))
b = querysetB.annotate(custom_order=Value(2))
a.union(b).order_by('custom_order')

之前,您需要为 Value 指定 output_field:

from django.db.models import IntegerField


a = querysetA.annotate(custom_order=Value(1, IntegerField()))
b = querysetB.annotate(custom_order=Value(2, IntegerField()))