Member-only story
Understanding Validators in Django REST Framework
Validation is a crucial part of any API. It ensures that data submitted by users meets certain requirements before being processed.
In Django REST Framework (DRF), validation is primarily handled at the serializer level, providing a clean and structured way to enforce constraints on incoming data.
This article explores DRF validators, their types, how they work, and how you can write custom validators for your API.
Validation in Django REST Framework
Unlike Django’s ModelForm
, where validation is split between the form and model, DRF performs all validation within the serializer. This separation offers several advantages:
- Clear Separation of Concerns: The model focuses on data storage, while the serializer handles input validation.
- Better Code Maintainability: You can switch between
ModelSerializer
andSerializer
classes without changing validation behavior. - Explicit Validation Rules: The validation logic is always visible when inspecting a serializer.
For instance, consider a CustomerReportRecord
model:
from django.db import models
from django.utils import timezone
class CustomerReportRecord(models.Model):
time_raised = models.DateTimeField(default=timezone.now, editable=False)
reference = models.CharField(unique=True, max_length=20)
description = models.TextField()