django distinct和order_by [英] django distinct and order_by
问题描述
Foo.objects.all()。distinct('foo')
不会删除重复
Foo.objects.all()。order_by()。distinct('foo')
将删除它们。
我有Meta.ordering =('-field1','-field2)
I have Meta.ordering = ('-field1', '-field2)
Foo.objects.all()。order_by()。 distinct('foo')
尊重Meta.ordering?
即我想要由Meta.ordering排序的不同的值,不知道该怎么做。
Does Foo.objects.all().order_by().distinct('foo')
respects the Meta.ordering?
i.e. I want distinct values ordered by Meta.ordering and not sure how to do it.
Django文件令人困惑,不解决如何 order_by()
,而没有任何参数。
Django Documentation is confusing and don't address how order_by()
without any argument works.
我正在使用postgresql 9.3 btw。
I'm using postgresql 9.3 btw.
In [28]: BestMomsdiaryThread.objects.all().values_list('momsdiary_thread__id', flat=True)
Out[28]: [3390, 5877, 5884, 6573, 5880, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, 6576, '...(remaining elements truncated)...']
In [29]: BestMomsdiaryThread.objects.not_deleted().order_by().distinct('momsdiary_thread').values_list('momsdiary_thread__id', flat=True)
Out[29]: [3390, 5877, 5880, 5884]
In [30]: BestMomsdiaryThread.objects.not_deleted().values_list('momsdiary_thread__id', flat=True)
Out[30]: [3390, 5877, 5884, 5880, 5877, 5880, 5884, 3390]
In [32]: BestMomsdiaryThread.objects.not_deleted().order_by('momsdiary_thread').distinct('momsdiary_thread').values_list('momsdiary_thread__id', flat=True)
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("momsplanner_bestmomsdiarythread"."momsd...
^
推荐答案
如果您不希望将任何订单应用于查询,甚至不要使用默认排序,请调用order_by(),而无参数。
If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.
这篇关于django distinct和order_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!