select distinct on expressions must match initial order by expressions sqlalchemy postgres 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')