【发布时间】:2014-02-07 07:33:47
【问题描述】:
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...
^
【问题讨论】:
-
@danihp: 是的,但你必须提供
order_by()不带任何参数,我不确定这是否会尊重 Meta.ordering。 -
order_by()没有参数不尊重元排序。它旨在从模型元中清除继承顺序,以提高不需要排序的性能(请记住,顺序可能包括引用的字段和连接)。一切都在文档中。 -
@danihp:感谢您的帮助。这是因为我不能在 order_by 中使用对象本身。我不得不使用 order_by('momsdiary_thread_id') 而不是 ('momsdiary_thread')。如果您发布答案,我可以接受