【问题标题】:python Django ORM group and order a querysetpython Django ORM 组并订购查询集
【发布时间】:2023-03-10 09:54:01
【问题描述】:

在我的 django 项目中,我必须使用 ORM 实现分组查询,并对特定字段的结果进行排序。 我这样做:

a = tt.objects.filter(thread_status = 'DEAD').select_related().distinct('thread_stag').order_by('-id')[0:20]

但响应是错误的:

ProgrammingError: SELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式

如何在不同列的同一查询中执行 distinct 和 order_by?

提前致谢

【问题讨论】:

    标签: python django orm django-queryset


    【解决方案1】:

    你可以试试这个吗? references from

    a = tt.objects.filter(thread_status = 'DEAD').select_related()\
                  .distinct('thread_stag').order_by('thread_stag', '-id')[0:20]
    

    a = tt.objects.filter(thread_status = 'DEAD').select_related()\
                  .order_by('thread_stag', '-id').distinct('thread_stag')[0:20]
    

    【讨论】:

    • 非常感谢,您的查询系统没有返回任何错误但结果未排序
    • 因为第一个订单是给thread_stag的,我只需要为id排序结果。提前致谢
    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2021-03-31
    • 2012-03-28
    • 2021-07-02
    相关资源
    最近更新 更多