Distinct records in django ORM

Getting distinct records from the database is very common requirement. Here is the django ORM query to get the distinct records in Django.

queryset = ModelClassName.objects.filter(FilterCondition)

queryset = queryset.distinct().all()

.filter() returns a queryset which can be further modified. We can apply distinct() clause on queryset.

Result of above ORM query will be equivalent to raw sql query showing below:

select distinct modelClassName.fieldName1, modelClassName.fieldName2 from modelClassName where <>

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top