django独特和order_by

eug*_*ene 3 django django-queryset

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排序的不同值,并且不确定如何执行。

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...


                      ^
Run Code Online (Sandbox Code Playgroud)

小智 5

来自https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by

如果您不希望对查询应用任何排序,甚至不希望使用默认排序,请调用不带参数的order_by()。