In API engineering, serializers perform the heavy lifting of converting database records into clean JSON payloads and verifying that incoming data from mobile or web clients complies with strict business validation rules.
# blog/serializers.py
from rest_framework import serializers
from .models import BlogPost, Comment, Category
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['id', 'name', 'slug']
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ['id', 'author_name', 'body', 'created_at']
read_only_fields = ['created_at']
class BlogPostDetailSerializer(serializers.ModelSerializer):
# Nested representation of Category
category = CategorySerializer(read_only=True)
# Write-only ID field to allow clients to assign a category by primary key
category_id = serializers.PrimaryKeyRelatedField(
queryset=Category.objects.all(),
source='category',
write_only=True
)
# Nested list of child comments
comments = CommentSerializer(many=True, read_only=True)
# Computed read-only field
word_count = serializers.SerializerMethodField()
class Meta:
model = BlogPost
fields = [
'id', 'title', 'slug', 'category', 'category_id',
'summary', 'content', 'word_count', 'comments', 'created_at'
]
read_only_fields = ['slug', 'created_at']
def get_word_count(self, obj):
return len(obj.content.split())
def validate_title(self, value):
"""Field-level validator: Ensure titles are sufficiently descriptive."""
if len(value.strip()) < 5:
raise serializers.ValidationError("Title must be at least 5 characters long.")
return value
def validate(self, data):
"""Object-level cross-field validation."""
title = data.get('title', '')
summary = data.get('summary', '')
if title.lower() in summary.lower():
raise serializers.ValidationError({"summary": "Summary must add new info, not duplicate the title."})
return data
| Capability | serializers.Serializer | serializers.ModelSerializer |
|---|---|---|
| Field Generation | Manual declaration for every single field. | Auto-inspected from Django Model definitions. |
| Validation Rules | Manual validators declared per field. | Model validators & uniqueness auto-applied. |
| Database CRUD | Must implement custom create() and update(). |
Default create() and update() provided. |
| Best Fit | Custom non-model payloads, complex forms, external APIs. | Standard database-backed RESTful CRUD APIs. |
When you need to reshape the outgoing JSON payload without altering your database models, override the to_representation() method:
def to_representation(self, instance):
data = super().to_representation(instance)
# Add human-friendly metadata
data['formatted_date'] = instance.created_at.strftime('%B %d, %Y')
data['reading_summary'] = f"{instance.reading_time_minutes} minutes read"
return data
SerializerMethodField is read-only. DRF automatically looks for a method named get_<field_name>(self, obj) on the serializer class, allowing you to compute dynamic metrics or URLs on the fly.
Broaden your backend architecture, REST API design, and production engineering expertise:
Get started with rest_framework and basic API views.
Plug ModelSerializers into GenericAPIView and ModelViewSet.
Compare Django ModelForm validation with DRF Serializer validation.
Auto-generate schema documentation directly from serializer field definitions.