如何链接Django查询集以保留单个顺序 [英] How to chain Django querysets preserving individual order

查看:78
本文介绍了如何链接Django查询集以保留单个顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django中附加或链接多个查询集,以保留每个查询集的顺序(而不是结果)。我正在使用第三方库对结果进行分页,它仅接受列表或查询集。我尝试了以下选项:

I'd like to append or chain several Querysets in Django, preserving the order of each one (not the result). I'm using a third-party library to paginate the result, and it only accepts lists or querysets. I've tried these options:

查询集联接:不会在单个查询集中保留顺序,因此我不能使用它。 / p>

Queryset join: Doesn't preserve ordering in individual querysets, so I can't use this.

result = queryset_1 | queryset_2

使用itertools :调用 list()链对象上的实际上会评估查询集,这可能会导致很多开销。

Using itertools: Calling list() on the chain object actually evaluates the querysets and this could cause a lot of overhead. Doesn't it?

result = list(itertools.chain(queryset_1, queryset_2))

您认为我应该怎么去?

推荐答案

此解决方案可防止重复:

This solution prevents duplicates:

q1 = Q(...)
q2 = Q(...)
q3 = Q(...)
qs = (Model.objects
      .filter(q1 | q2 | q3)
      .annotate(
          search_type_ordering=Case(
              When(q1, then=Value(2)),
              When(q2, then=Value(1)),
              When(q3, then=Value(0)),
              default=Value(-1),
              output_field=IntegerField()))
      .order_by('-search_type_ordering', ...))

这篇关于如何链接Django查询集以保留单个顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆