Serializer validation helps check if the data sent to your Django app is correct and safe before saving or using it.
Serializer validation in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
from rest_framework import serializers class MySerializer(serializers.Serializer): field_name = serializers.CharField(max_length=100) def validate_field_name(self, value): # custom validation for field_name if 'bad' in value: raise serializers.ValidationError("No 'bad' allowed!") return value def validate(self, data): # validation for multiple fields together if data.get('field_name') == 'forbidden': raise serializers.ValidationError("This value is forbidden.") return data
validate_field_name checks one field at a time.
validate checks the whole data dictionary for rules involving multiple fields.
Examples
Django
class UserSerializer(serializers.Serializer): username = serializers.CharField() def validate_username(self, value): if ' ' in value: raise serializers.ValidationError("Username cannot contain spaces.") return value
Django
class ProductSerializer(serializers.Serializer): price = serializers.FloatField() discount = serializers.FloatField() def validate(self, data): if data['discount'] > data['price']: raise serializers.ValidationError("Discount cannot be more than price.") return data
Sample Program
This serializer checks that pages is positive and title is not the same as author (case insensitive). It prints errors if validation fails.
Django
from rest_framework import serializers class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=50) author = serializers.CharField(max_length=50) pages = serializers.IntegerField() def validate_pages(self, value): if value <= 0: raise serializers.ValidationError("Pages must be a positive number.") return value def validate(self, data): if data['title'].lower() == data['author'].lower(): raise serializers.ValidationError("Title and author cannot be the same.") return data # Example usage serializer = BookSerializer(data={ 'title': 'Django Basics', 'author': 'django basics', 'pages': 100 }) if not serializer.is_valid(): print(serializer.errors) else: print("Data is valid")
Important Notes
Always call is_valid() before accessing validated data or saving.
Field-level validation methods must be named validate_.
Use validate() for rules involving multiple fields.
Summary
Serializer validation checks data correctness before use.
Use validate_<field> for single fields and validate() for multiple fields.
Validation errors help give clear feedback to users or API clients.
Practice
1. What is the main purpose of serializer validation in Django REST Framework?
easy
Solution
Step 1: Understand serializer validation role
Serializer validation ensures the data received is correct and meets rules before using it.Step 2: Differentiate from other serializer tasks
Saving data or formatting output are separate steps; validation happens first to prevent errors.Final Answer:
To check if the input data is correct before saving or processing -> Option AQuick Check:
Validation = Data correctness check [OK]
Hint: Validation checks data correctness before saving or using it [OK]
Common Mistakes:
- Confusing validation with saving data
- Thinking validation formats output
- Assuming validation creates database tables
2. Which method name is correct to validate a single field called
email in a serializer?easy
Solution
Step 1: Recall Django REST Framework naming convention
Single field validation methods must be namedvalidate_<fieldname>.Step 2: Match method name to field
The correct method isemailvalidate_email, exactly matching the field name.Final Answer:
validate_email -> Option DQuick Check:
Single field validator = validate_fieldname [OK]
Hint: Use validate_ plus field name exactly for single field validation [OK]
Common Mistakes:
- Using camelCase instead of snake_case
- Adding extra words like 'field' in method name
- Using incorrect prefixes like 'check_'
3. Given this serializer code, what will happen if
age is less than 18?
class UserSerializer(serializers.Serializer):
age = serializers.IntegerField()
def validate_age(self, value):
if value < 18:
raise serializers.ValidationError('Must be at least 18')
return value
medium
Solution
Step 1: Understand the validate_age method logic
The method checks if age is less than 18 and raises ValidationError if true.Step 2: Predict behavior when age < 18
If age is less than 18, the error is raised stopping validation and returning the message.Final Answer:
ValidationError with message 'Must be at least 18' is raised -> Option AQuick Check:
Age < 18 triggers ValidationError [OK]
Hint: ValidationError raised when condition inside validate_<field> fails [OK]
Common Mistakes:
- Assuming age is changed automatically
- Thinking no error occurs for invalid age
- Believing the field is ignored silently
4. Identify the error in this serializer validation code:
class ProductSerializer(serializers.Serializer):
price = serializers.FloatField()
def validate(self, data):
if data['price'] < 0:
raise serializers.ValidationError('Price must be positive')
return data
def validate_price(self, value):
if value == 0:
raise serializers.ValidationError('Price cannot be zero')
return value
medium
Solution
Step 1: Check validate_price method
It correctly checks if value is zero and raises error, then returns value.Step 2: Check validate method
It checks if price is negative and raises error, then returns data dictionary.Step 3: Confirm ValidationError usage
Passing string message is allowed; dictionary is optional for field-specific errors.Final Answer:
No error, code is correct -> Option CQuick Check:
Both validate and validate_<field> methods are valid [OK]
Hint: Both validate and validate_<field> can coexist and return correct types [OK]
Common Mistakes:
- Expecting validate_price to return data dict
- Thinking super().validate(data) is mandatory
- Believing ValidationError must be dict only
5. You want to validate that
start_date is before end_date in a serializer. Which is the best way to do this?hard
Solution
Step 1: Understand single field validators scope
Methods like validate_start_date only receive one field's value, so cannot compare two fields.Step 2: Use validate method for multi-field validation
The validate(self, data) method receives all fields and can compare start_date and end_date together.Final Answer:
Use the validate(self, data) method to compare both fields -> Option BQuick Check:
Multi-field validation = validate(data) method [OK]
Hint: Use validate(data) for checks involving multiple fields [OK]
Common Mistakes:
- Trying to compare fields inside single field validators
- Ignoring multi-field validation method
- Doing validation only outside serializer
