Django REST Serializer Validation Fix
In this tutorial, you'll learn about Django REST Serializer Validation Fix. We cover key concepts, practical examples, and best practices.
The Problem
Default DRF serializers validate types and basic constraints, but business rules like "end date must be after start date" or "username must be unique across active users" need custom validation.
Quick Fix
Wrong — validation in the view
class BookingView(APIView):
def post(self, request):
serializer = BookingSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
# Broken — view shouldn't validate business rules
if serializer.validated_data['end'] < serializer.validated_data['start']:
return Response({'error': 'End must be after start'}, status=400)
Output: Works but scatters validation logic. Other views reimplement the same check.
Correct — field-level validation
class BookingSerializer(serializers.Serializer):
start = serializers.DateTimeField()
end = serializers.DateTimeField()
def validate_end(self, value):
start = self.initial_data.get('start')
if start and value < start:
raise serializers.ValidationError("End must be after start")
return value
Correct — object-level validation
class BookingSerializer(serializers.Serializer):
def validate(self, data):
if data['end'] <= data['start']:
raise serializers.ValidationError("End must be after start")
if self._overlaps(data):
raise serializers.ValidationError("Time slot overlaps existing booking")
return data
Unique together validation
def validate(self, data):
if Booking.objects.filter(
room=data['room'],
start__lt=data['end'],
end__gt=data['start'],
).exists():
raise serializers.ValidationError("Room already booked")
return data
Prevention
- Use
validate_<field_name>for single-field validation. - Use
validate()for cross-field and database-dependent rules. - Never put business validation in views — keep it in the serializer.
Common Mistakes with rest serializer validation
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
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