Foo.objects.all().distinct('foo')
不会去除重复项。
Foo.objects.all().order_by().distinct('foo')
会去除它们。
我有一个 Meta.ordering = ('-field1', '-field2)
Foo.objects.all().order_by().distinct('foo')
是否遵守 Meta.ordering?
即,我想要按照 Meta.ordering 排序的不同值,但不确定如何实现。
Django 文档很混乱,没有解释 order_by()
在没有任何参数的情况下是如何工作的。
顺便说一下,我正在使用 postgresql 9.3。
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()
,而且我不确定它是否会遵守 Meta.ordering。 - eugeneorder_by()
没有参数时,不会遵循元模型的排序。它旨在清除从模型元中继承的排序,以提高在不需要排序的情况下的性能(请记住,排序可能包括引用字段和连接)。所有内容都在文档中。 - dani herrera