【问题标题】:Django Query, Distinct and Order_By combination not workingDjango Query、Distinct 和 Order_By 组合不起作用
【发布时间】:2016-12-17 10:49:58
【问题描述】:

这里有类似的问题,但我找不到对我有帮助的问题。

我有两个模型,Chat 和 Post

有多个聊天,每个聊天都附有多个帖子。 我正在尝试获取每次聊天的最新帖子。

Post.objects.order_by('-id').distinct('Chat')

按 ID 过滤帖子(因此最新帖子在前),然后根据聊天获取不同的帖子。

但由于 order_by 和 distinct 不匹配,我得到了错误:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions

那么我究竟该如何做呢?原始数据库?谢谢!

【问题讨论】:

    标签: django postgresql django-queryset


    【解决方案1】:

    如果您使用相关型号的distinct,您必须使用基于此型号的订购:
    Post.objects.order_by('chat', '-id').distinct('chat')
    也可以看at this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2019-08-06
      • 2017-06-07
      • 2014-09-11
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多