Retrieving a Single Object with get()
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 command in your terminal.
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.
Warning: Unhandled DoesNotExist exceptions will crash a view with a 500 error.
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 command in your terminal.
Handling Too Many Matches
If more than one row matches the condition, .get() raises Book.MultipleObjectsReturned instead of silently picking one.
Warning: Use .filter() and .first() if you expect multiple matches but only want one result.
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 command in your terminal.
- 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: