2
Foo.objects.all().distinct('foo')
不會刪除重複Django的獨特和ORDER_BY
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 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...
^
只有在postgress中:[「對於具有指定字段名稱的distinct()調用,數據庫將只比較指定的字段名稱。」](https://docs.djangoproject.com/en/dev/ref /models/querysets/#django.db.models.query.QuerySet.distinct) – danihp
@danihp:是的,但是你必須提供'order_by()'而沒有參數,我不確定這是否會尊重Meta。排序。 – eugene
'order_by()'帶出參數*不尊重元排序。它旨在清除從模型meta訂購的繼承,以便在不需要排序的情況下提高性能(請記住,排序可能包括引用的字段和連接)。全部在文檔中。 – danihp