← Back to Django Course | Chapter 4: Models & Django ORM Basics | Lesson 7 of 10

Retrieving a Single Object with get()

get() is for when you know exactly one card in the cabinet matches, and you just want that one card handed to you directly, not a whole stack.

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.

bash
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.

bash
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.

bash
try:
    book = Book.objects.get(genre='Action')
except Book.MultipleObjectsReturned:
    print('More than one match')

⚠️ Run this command in your terminal.

Common Mistakes
  1. Using .get() on a condition that could match zero or many rows, which raises DoesNotExist or MultipleObjectsReturned.
  2. Not wrapping .get() in a try/except when the object might not exist, crashing the whole view.
  3. Using .get() inside a loop to fetch related objects one at a time instead of using a single filter or select_related.
Chapter Summary
  • 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.