🎯 Django QuerySet Get – Retrieve a Single Record with .get()
(2025 Guide)
🧲 Introduction – What Is .get()
in Django QuerySet?
The .get()
method is used in Django to retrieve exactly one object from the database that matches a specified condition. It’s ideal when you know you’re retrieving a unique record, like a post by ID or a user by username.
🎯 In this guide, you’ll learn:
- How to use
.get()
properly - What exceptions it raises and how to handle them
- When to use
.get()
vs..filter()
- Best practices for safe record retrieval
🧱 Basic Syntax
Model.objects.get(field=value)
✅ Returns the object that matches the condition.
🧪 Example Usage
Model:
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
View:
from blog.models import Post
post = Post.objects.get(slug='django-intro')
✔️ Fetches the unique post where slug = 'django-intro'
.
⚠️ Exceptions to Handle
🔴 DoesNotExist
Raised if no record matches the condition.
from django.core.exceptions import ObjectDoesNotExist
try:
post = Post.objects.get(id=10)
except Post.DoesNotExist:
post = None
🔴 MultipleObjectsReturned
Raised if more than one record matches (which .get()
cannot handle):
try:
post = Post.objects.get(title='News')
except Post.MultipleObjectsReturned:
# Use .filter() instead
🔍 When to Use .get()
vs .filter()
Use Case | Method to Use |
---|---|
Only one object should exist | .get() |
Multiple objects may exist | .filter() |
You want a list/queryset | .filter() |
You expect exactly one item | .get() |
📘 Real-World Example
Get a user profile by username:
from django.contrib.auth.models import User
try:
user = User.objects.get(username='johndoe')
except User.DoesNotExist:
user = None
✅ Best Practices
- ✅ Always wrap
.get()
in a try/except block - ✅ Use
.filter().first()
or.filter().exists()
if unsure about match count - ✅ Use
.get()
only when field is guaranteed unique (likeid
,slug
,username
) - ✅ Never chain
.get()
—it must be the final method
📌 Summary – Recap & Next Steps
🔍 Key Takeaways:
.get()
retrieves a single object matching a query- Raises errors if none or multiple objects are found
- Best used with unique identifiers like primary keys
- Wrap in
try/except
for safe usage
⚙️ Real-World Relevance:
Perfect for detail pages, dashboards, profile fetches, and lookups where you expect a single match from the database.
❓ Frequently Asked Questions (FAQ)
❓ What happens if .get()
finds no records?
🚫 Raises DoesNotExist
. Always wrap it in try/except
.
❓ What if two records match my .get()
?
🚫 Raises MultipleObjectsReturned
. Use .filter()
instead.
❓ Can I use .get()
with multiple conditions?
✅ Yes:
Post.objects.get(slug='django-intro', status='published')
❓ Can I use .get()
with foreign key fields?
✅ Yes. Use:
Comment.objects.get(post__id=1)
❓ Is .get()
faster than .filter()
?
🟡 Not necessarily—it depends on the index and query. But .get()
is more concise for retrieving a single item.
Share Now :