django distinct and order_by

2019-05-14 01:23发布

问题:

Foo.objects.all().distinct('foo') won't remove duplicates

Foo.objects.all().order_by().distinct('foo') does remove them.

I have Meta.ordering = ('-field1', '-field2)

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 Documentation is confusing and don't address how order_by() without any argument works.

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


                      ^

回答1:

From https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.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.