在我的 Django 项目中,我必须使用 ORM 实现分组查询并为特定字段排序结果。 我这样做:
a = tt.objects.filter(thread_status = 'DEAD').select_related().distinct('thread_stag').order_by('-id')[0:20]
但是响应是错误的:
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
如何在不同列的同一查询中执行 distinct 和 order_by?
提前致谢
最佳答案
你能试试这个吗? 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]
关于python Django ORM组并订购查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241130/