Retrieving a Single Object with get()
try:
obj = ModelName.objects.get(field=value)
except ModelName.DoesNotExist:
# handle missing object
Fetching One Object
Model.objects.get(field=value) returns exactly one matching object directly — not wrapped in a QuerySet — when you're sure only one row matches.
Example: Fetching One Object
Model.objects.get(field=value) returns exactly one matching object directly — not wrapped in a QuerySet — when you're sure only one row matches.
book = Book.objects.get(id=1)
print(book.title)
⚠️ Run this in your own terminal or Node.js environment.
Handling a Missing Object
If no row matches the condition, .get() raises Book.DoesNotExist. Wrap it in a try/except to handle that case gracefully.
Example: Handling a Missing Object
If no row matches the condition, .get() raises Book.DoesNotExist. Wrap it in a try/except to handle that case gracefully.
try:
book = Book.objects.get(id=999)
except Book.DoesNotExist:
print('No book with that id')
⚠️ Run this in your own terminal or Node.js environment.
Handling Too Many Matches
If more than one row matches the condition, .get() raises Book.MultipleObjectsReturned instead of silently picking one.
Example: Handling Too Many Matches
If more than one row matches the condition, .get() raises Book.MultipleObjectsReturned instead of silently picking one.
try:
book = Book.objects.get(genre='Action')
except Book.MultipleObjectsReturned:
print('More than one match')
⚠️ Run this in your own terminal or Node.js environment.
- Using .get() on a condition that could match zero or many rows, which raises DoesNotExist or MultipleObjectsReturned.
- Not wrapping .get() in a try/except when the object might not exist, crashing the whole view.
- Using .get() inside a loop to fetch related objects one at a time instead of using a single filter or select_related.
- Model.objects.get(...) returns exactly one object, not a QuerySet.
- If no object matches, Django raises Model.DoesNotExist.
- If more than one object matches, Django raises Model.MultipleObjectsReturned.
- get() is best used with a unique field, like the primary key or an id, to guarantee a single match.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: