How to Use Distinct in Django: Syntax and Examples
In Django, use the
distinct() method on a QuerySet to return unique records by removing duplicates. You can call distinct() without arguments for all fields or with specific field names to get distinct results based on those fields.Syntax
The distinct() method is called on a Django QuerySet to filter out duplicate rows from the query results.
distinct(): Returns unique rows based on all fields.distinct('field1', 'field2'): Returns unique rows based on the specified fields (PostgreSQL only).
python
queryset = Model.objects.filter(condition).distinct() # Or with specific fields (PostgreSQL only): queryset = Model.objects.distinct('field1', 'field2')
Example
This example shows how to get unique authors from a Book model where multiple books may have the same author.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) # Query to get distinct authors unique_authors = Book.objects.values('author').distinct() for author in unique_authors: print(author['author'])
Output
Alice
Bob
Charlie
Common Pitfalls
One common mistake is using distinct() with field names on databases other than PostgreSQL, which will cause errors. Also, using distinct() without values() or values_list() may not remove duplicates as expected if the QuerySet includes related fields.
Wrong way (field names on SQLite or MySQL):
python
# This will raise an error on SQLite or MySQL Book.objects.distinct('author') # Correct way for all databases: Book.objects.values('author').distinct()
Quick Reference
- distinct(): Removes duplicate rows from QuerySet.
- distinct('field'): Removes duplicates based on fields (PostgreSQL only).
- Use
values()orvalues_list()withdistinct()to get unique field values. - Works best with simple queries; complex joins may affect distinct behavior.
Key Takeaways
Use distinct() on a QuerySet to get unique records by removing duplicates.
distinct('field') works only on PostgreSQL to get unique rows by specific fields.
Combine distinct() with values() or values_list() to get unique field values.
Avoid using distinct(field) on databases other than PostgreSQL to prevent errors.
distinct() helps clean up query results when duplicates appear due to joins or filters.