Skip to content

Django REST Serializer Validation Fix

DodaTech Updated 2026-06-24 2 min read

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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What's the difference between validators and validate methods?

Validators are reusable callables applied to a field. validate_<field> and validate are serializer methods for one-off or cross-field logic.

When does is_valid() run validation?

is_valid() triggers all validators and validate methods. It returns False if any validation fails. Call raise_exception=True to get a 400 response automatically.

Can I access the request in validation?

Yes: self.context['request'] is available inside validate methods.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro