Django distinct group by query on two fields

Today I faced the same problem. In Django admin in get_queryset method I needed to make the distinct operation in multiple fields. I solved this problem this way:

from django.db.models import TextField
from django.db.models.functions import Concat
Mymodel.objects.filter(...).annotate(distinct_name=Concat('tcode', 'created_on', output_field=TextField())).order_by('distinct_name').distinct('distinct_name')

This decision helps to return QuerySet with ID of the record


I don't think there's one single query that could do this, because there's no mechanism from database to pick random one from duplicates. However, if you only care about those two fields, you could do:

MyModel.objects.order_by('tcode').values('tcode', 'created_on').distinct()

This won't give you complete MyModel objects, but a list of dictionaries that contain all the existing combinations of tcode and created_on.