Interview question
What is the difference between QuerySet.filter(), .exclude(), and .get()? QuerySet.filter(), .exclude(), .get() में क्या अंतर है?
Answer
| Method | Returns | No match behavior | Multiple matches behavior |
|---|---|---|---|
| filter() | QuerySet (possibly empty) | Returns empty QuerySet | Returns all matches |
| exclude() | QuerySet (inverse of filter) | Returns empty QuerySet | Returns all non-matches |
| get() | A single model instance | Raises DoesNotExist | Raises MultipleObjectsReturned |
from myapp.models import Book
# filter() - returns a QuerySet, safe even with zero results
cheap_books = Book.objects.filter(price__lt=20)
print(cheap_books) # <QuerySet [...]> - could be empty, no error
# exclude() - opposite of filter, returns non-matching rows
expensive_books = Book.objects.exclude(price__lt=20)
# get() - expects EXACTLY one result
try:
book = Book.objects.get(id=1) # returns a single Book instance directly
except Book.DoesNotExist:
print('Book not found')
except Book.MultipleObjectsReturned:
print('More than one book matched - id should be unique!')
# Chaining filter() calls - each filter narrows the QuerySet further
results = Book.objects.filter(price__lt=50).filter(author__name='John')
# Common field lookups used with filter()/exclude()
Book.objects.filter(title__icontains='django') # case-insensitive contains
Book.objects.filter(price__gte=10, price__lte=50) # range
Book.objects.filter(published_date__year=2024) # date component
Book.objects.filter(author__name__startswith='J') # traverse relationships
# Combining conditions with Q objects for OR logic
from django.db.models import Q
Book.objects.filter(Q(price__lt=20) | Q(author__name='John'))| Method | Return | कोई match नहीं मिलने पर | Multiple matches पर |
|---|---|---|---|
| filter() | QuerySet | Empty QuerySet | सभी matches |
| exclude() | QuerySet (उल्टा) | Empty QuerySet | सभी non-matches |
| get() | एक model instance | DoesNotExist raise | MultipleObjectsReturned raise |
from myapp.models import Book
cheap_books = Book.objects.filter(price__lt=20)
print(cheap_books)
expensive_books = Book.objects.exclude(price__lt=20)
try:
book = Book.objects.get(id=1)
except Book.DoesNotExist:
print('Book नहीं मिली')
except Book.MultipleObjectsReturned:
print('एक से ज़्यादा books match हुईं!')
results = Book.objects.filter(price__lt=50).filter(author__name='John')
Book.objects.filter(title__icontains='django')
Book.objects.filter(price__gte=10, price__lte=50)
Book.objects.filter(published_date__year=2024)
Book.objects.filter(author__name__startswith='J')
from django.db.models import Q
Book.objects.filter(Q(price__lt=20) | Q(author__name='John'))Was this answer clear?