ELECT DISTINCT ON expressions must match initial ORDER BY expressions code example
Example: SELECT DISTINCT ON expressions must match initial ORDER BY expressions django
from django.db.models import Subquery
Model.objects.filter(
pk__in=Subquery(
Model.objects.all().distinct('foo').values('pk')
)
).order_by('bar')