← Back to Python

All Topics

Advertisement

Learn/Python/Web Development

REST Framework Serializers Deep Dive

Topic: Django

Advertisement

Introduction

Advanced serializer features including nested serializers and custom fields.

Nested Serializers

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ["id", "name"]

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(read_only=True)
    author_id = serializers.PrimaryKeyRelatedField(
        queryset=Author.objects.all(),
        source="author",
        write_only=True
    )
    
    class Meta:
        model = Book
        fields = ["id", "title", "author", "author_id", "price"]

Serializer Methods

class BookSerializer(serializers.ModelSerializer):
    author_name = serializers.SerializerMethodField()
    discounted_price = serializers.SerializerMethodField()
    
    def get_author_name(self, obj):
        return obj.author.name
    
    def get_discounted_price(self, obj):
        return obj.price * 0.9  # 10% discount
    
    class Meta:
        model = Book
        fields = ["title", "author_name", "price", "discounted_price"]

Validation

class BookSerializer(serializers.ModelSerializer):
    def validate_price(self, value):
        if value <= 0:
            raise serializers.ValidationError("Price must be positive")
        return value
    
    def validate(self, data):
        if data.get("published_date") > timezone.now().date():
            raise serializers.ValidationError("Cannot publish future books")
        return data

Practice Problems

  1. Create nested serializer relationships
  2. Add custom validation logic
  3. Implement SerializerMethodField
  4. Create write-only nested serializers
  5. Add multiple validation methods

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →