【问题标题】:Django merge QuerySet while keeping the orderDjango在保持顺序的同时合并QuerySet
【发布时间】:2021-11-22 13:36:09
【问题描述】:

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

我当前的代码是:

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

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

【问题讨论】:

  • 它在数据库中创建了一个联合查询,所以不是不可能(至少一般情况下是这样)。

标签: python django django-models django-queryset


【解决方案1】:

这可以通过使用 annotate 添加自定义字段以在查询集上进行排序来解决,并在 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()))

【讨论】:

  • 谢谢,这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
相关资源
最近更新 更多