Bird
Raised Fist0
Djangoframework~20 mins

Serializer validation in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Serializer Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this serializer validation code?

Consider this Django REST Framework serializer:

from rest_framework import serializers

class ProductSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    price = serializers.DecimalField(max_digits=5, decimal_places=2)

serializer = ProductSerializer(data={'name': 'Pen', 'price': '12.345'})
valid = serializer.is_valid()
errors = serializer.errors

What will be the value of valid and errors after running this code?

Django
from rest_framework import serializers

class ProductSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    price = serializers.DecimalField(max_digits=5, decimal_places=2)

serializer = ProductSerializer(data={'name': 'Pen', 'price': '12.345'})
valid = serializer.is_valid()
errors = serializer.errors
Avalid is False; errors contain {'price': ['Ensure that there are no more than 2 decimal places.']}
Bvalid is True; errors is an empty dict {}
Cvalid is False; errors contain {'name': ['This field is required.']}
Dvalid is True; errors contain {'price': ['Invalid decimal value.']}
Attempts:
2 left
💡 Hint

Check how DecimalField validates decimal places.

state_output
intermediate
2:00remaining
What is the value of validated_data after calling is_valid()?

Given this serializer and data:

from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    age = serializers.IntegerField(min_value=18)

serializer = UserSerializer(data={'username': 'alice', 'age': 17})
serializer.is_valid()
validated = serializer.validated_data

What will be the value of validated?

Django
from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    age = serializers.IntegerField(min_value=18)

serializer = UserSerializer(data={'username': 'alice', 'age': 17})
serializer.is_valid()
validated = serializer.validated_data
ARaises a ValidationError because validated_data is not set when validation fails
B{'username': 'alice', 'age': 17}
C{} (empty dict)
DNone
Attempts:
2 left
💡 Hint

Think about what happens when is_valid() returns False.

📝 Syntax
advanced
2:00remaining
Which option correctly implements a custom field-level validation method?

In Django REST Framework serializers, how do you correctly write a custom validation method for the field email?

Django
from rest_framework import serializers

class ContactSerializer(serializers.Serializer):
    email = serializers.EmailField()

    # Custom validation method here
A
def validate_email(self):
    if not self.email.endswith('@example.com'):
        raise serializers.ValidationError('Email must be from example.com')
    return self.email
B
def validate(self, data):
    if not data['email'].endswith('@example.com'):
        raise serializers.ValidationError('Email must be from example.com')
    return data
C
def validate_email(self, value):
    if not value.endswith('@example.com'):
        raise serializers.ValidationError('Email must be from example.com')
    return value
D
def validate_email(value):
    if not value.endswith('@example.com'):
        raise serializers.ValidationError('Email must be from example.com')
    return value
Attempts:
2 left
💡 Hint

Field-level validation methods must be named validate_ and accept self and value.

🔧 Debug
advanced
2:00remaining
Why does this serializer raise a KeyError during validation?

Look at this serializer code:

from rest_framework import serializers

class OrderSerializer(serializers.Serializer):
    product_id = serializers.IntegerField(read_only=True)
    quantity = serializers.IntegerField()

    def validate(self, data):
        if data['quantity'] > 10 and data['product_id'] == 0:
            raise serializers.ValidationError('Invalid order')
        return data

serializer = OrderSerializer(data={'quantity': 15})
serializer.is_valid()

Why does calling is_valid() raise a KeyError?

Django
from rest_framework import serializers

class OrderSerializer(serializers.Serializer):
    product_id = serializers.IntegerField(read_only=True)
    quantity = serializers.IntegerField()

    def validate(self, data):
        if data['quantity'] > 10 and data['product_id'] == 0:
            raise serializers.ValidationError('Invalid order')
        return data

serializer = OrderSerializer(data={'quantity': 15})
serializer.is_valid()
ABecause 'quantity' is missing in input data, causing KeyError
BBecause 'product_id' is missing in input data, accessing data['product_id'] causes KeyError
CBecause validate method must return None, not data
DBecause serializers.IntegerField() does not accept missing fields
Attempts:
2 left
💡 Hint

Check which fields are required and what keys exist in data inside validate().

🧠 Conceptual
expert
2:00remaining
Which option best describes the order of validation methods called in a serializer?

In Django REST Framework, when you call serializer.is_valid(), in what order are the following validation methods called?

  • Field-level validation methods (e.g., validate_)
  • Object-level validation method (validate(self, data))
  • Built-in field validators
A1, 3, 2
B2, 1, 3
C3, 1, 2
D1, 2, 3
Attempts:
2 left
💡 Hint

Think about how DRF validates each field before running custom validations.

Practice

(1/5)
1. What is the main purpose of serializer validation in Django REST Framework?
easy
A. To check if the input data is correct before saving or processing
B. To automatically save data to the database
C. To format the output data for display
D. To create database tables automatically

Solution

  1. Step 1: Understand serializer validation role

    Serializer validation ensures the data received is correct and meets rules before using it.
  2. Step 2: Differentiate from other serializer tasks

    Saving data or formatting output are separate steps; validation happens first to prevent errors.
  3. Final Answer:

    To check if the input data is correct before saving or processing -> Option A
  4. Quick 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
A. validateEmail
B. validate_field_email
C. check_email
D. validate_email

Solution

  1. Step 1: Recall Django REST Framework naming convention

    Single field validation methods must be named validate_<fieldname>.
  2. Step 2: Match method name to field email

    The correct method is validate_email, exactly matching the field name.
  3. Final Answer:

    validate_email -> Option D
  4. Quick 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
A. ValidationError with message 'Must be at least 18' is raised
B. The age is automatically set to 18
C. No error, age is accepted as is
D. Serializer ignores the age field

Solution

  1. Step 1: Understand the validate_age method logic

    The method checks if age is less than 18 and raises ValidationError if true.
  2. Step 2: Predict behavior when age < 18

    If age is less than 18, the error is raised stopping validation and returning the message.
  3. Final Answer:

    ValidationError with message 'Must be at least 18' is raised -> Option A
  4. Quick 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
A. validate method should call super().validate(data)
B. validate_price should return data, not value
C. No error, code is correct
D. ValidationError messages must be dictionaries, not strings

Solution

  1. Step 1: Check validate_price method

    It correctly checks if value is zero and raises error, then returns value.
  2. Step 2: Check validate method

    It checks if price is negative and raises error, then returns data dictionary.
  3. Step 3: Confirm ValidationError usage

    Passing string message is allowed; dictionary is optional for field-specific errors.
  4. Final Answer:

    No error, code is correct -> Option C
  5. Quick 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
A. Use validate_start_date to compare both dates
B. Use the validate(self, data) method to compare both fields
C. Validate dates outside the serializer only
D. Use validate_end_date to compare both dates

Solution

  1. Step 1: Understand single field validators scope

    Methods like validate_start_date only receive one field's value, so cannot compare two fields.
  2. 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.
  3. Final Answer:

    Use the validate(self, data) method to compare both fields -> Option B
  4. Quick 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