Django MultipleObjectsReturned Fix
In this tutorial, you'll learn about Django MultipleObjectsReturned Fix. We cover key concepts, practical examples, and best practices.
The Problem
Django raises MultipleObjectsReturned: get() returned more than one ... -- it returned 2! when using get() to retrieve a single object. This happens when the query matches multiple rows.
Quick Fix
Step 1: Use filter() instead of get()
# Wrong -- crashes if multiple match
user = User.objects.get(email='test@example.com')
# Correct -- returns QuerySet
users = User.objects.filter(email='test@example.com')
if users.count() == 1:
user = users.first()
elif users.count() == 0:
user = None
else:
user = users.first()
Step 2: Add unique constraints
class User(models.Model):
email = models.EmailField(unique=True)
Expected: Run: python manage.py makemigrations && python manage.py migrate
Step 3: Find and fix duplicates
from django.db.models import Count
duplicates = User.objects.values('email').annotate(
count=Count('id')
).filter(count__gt=1)
for dup in duplicates:
users = User.objects.filter(email=dup['email'])
keep = users.first()
users.exclude(pk=keep.pk).delete()
Step 4: Handle gracefully in code
try:
user = User.objects.get(email='test@example.com')
except User.MultipleObjectsReturned:
user = User.objects.filter(email='test@example.com').first()
except User.DoesNotExist:
user = None
Step 5: Use get_or_create with defaults
user, created = User.objects.get_or_create(
email='test@example.com',
defaults={'username': 'test'}
)
Prevention
- Add unique=True to fields that should be unique.
- Use get_object_or_404() in views for single-object lookups.
- Add database-level unique constraints.
Common Mistakes with multiple objects
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro