Sobes.tech
Junior — Middle

How is data validation performed through serializers in Django REST Framework?

sobes.tech AI

Answer from AI

In Django REST Framework, data validation through serializers is performed using the is_valid() method. When this method is called, the serializer validates all fields based on the specified rules: data types, required fields, length constraints, custom validators, and validate_<fieldname> or validate methods.

If the data fails validation, the serializer.errors attribute contains a dictionary describing the errors. Validation can include both built-in checks and custom ones defined by the developer.

Example:

from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=100)
    age = serializers.IntegerField()

    def validate_age(self, value):
        if value < 18:
            raise serializers.ValidationError("Age must be at least 18")
        return value

serializer = UserSerializer(data={'username': 'ivan', 'age': 16})
if serializer.is_valid():
    valid_data = serializer.validated_data
else:
    print(serializer.errors)  # {'age': ['Age must be at least 18']}