Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 10 · Django Models & ORM
Interview question

What is the difference between QuerySet.filter(), .exclude(), and .get()? QuerySet.filter(), .exclude(), .get() में क्या अंतर है?

Answer
MethodReturnsNo match behaviorMultiple matches behavior
filter()QuerySet (possibly empty)Returns empty QuerySetReturns all matches
exclude()QuerySet (inverse of filter)Returns empty QuerySetReturns all non-matches
get()A single model instanceRaises DoesNotExistRaises 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'))
MethodReturnकोई match नहीं मिलने परMultiple matches पर
filter()QuerySetEmpty QuerySetसभी matches
exclude()QuerySet (उल्टा)Empty QuerySetसभी non-matches
get()एक model instanceDoesNotExist raiseMultipleObjectsReturned 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?