Search code examples
djangodjango-modelssql-order-bydjango-filtersdjango-aggregation

Django order_by() is not working along with distinct()


How can i use order_by() in combination with distinct() ?

I am having multiple same run_id with different end_time and trying to filter distinct run_id and order by end_time

data = list(table_name.objects.filter(experience=experience)\
.values('run_id', 'end_time').distinct('run_id').order_by('-end_time'))

Following is the error :-

django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions

However, the following ORM works fine without order_by but I want the latest end_time

data = list(table_name.objects.filter(experience=experience).values('run_id', 'end_time').distinct('run_id'))

Solution

  • What is database?

    Try:

    data = list(table_name.objects.filter(experience=experience)\
    .values('run_id', 'end_time').distinct('run_id').order_by('run_id', '-end_time'))[::1]