Django DRF - Part 02 - Serializers & Views
Bhuvan
Technical Staff

1. The "Translator": What is Serialization?
Think of a Serializer as a translator.
- Serialization: Translating a complex Python object (like a Product from your database) into a format the web understands, like JSON.
- Deserialization: Taking JSON data sent by a user (like when they create a new account) and converting it back into a Python object that Django can save to the database.
It is very similar to Django’s ModelForm. If Models define the database structure, Serializers define the API structure.
2. Data Flow Visualization
This sequence diagram shows exactly what happens when a user requests a product list from your E-commerce site.
3. The `ModelSerializer` & Validation
The ModelSerializer is a shortcut that automatically creates fields based on your Model.
Field-Level Validation
When a user sends data to your API, you need to ensure it is "clean." In DRF, you do this by writing methods following the naming convention: validate_<field_name>.
| Feature | Description |
|---|---|
Meta Class | Tells the serializer which model to use and which fields to include in the JSON. |
validate_price | A custom logic gate. If a user tries to set a price of -$5.00, the serializer will "raise" an error and stop the process. |
id Field | Even if not in your model explicitly, Django adds an id. Including it in the serializer helps the frontend identify specific items. |
4. Function-Based Views (FBVs)
To use the serializer, we create a view. We use the @api_view decorator to tell Django, "This isn't a normal webpage; this is an API endpoint."
many=True: Essential when you are returning a list of items (a QuerySet). Without it, the serializer expects a single object and will crash.get_object_or_404: A safety net. If a user looks for Product #999 and it doesn't exist, it automatically sends back a "404 Not Found" error instead of crashing the server.
5. Production-Ready Implementation
serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
# Explicitly listing fields is more secure than using '__all__'
fields = ('id', 'name', 'price', 'stock', 'in_stock')
# Custom Validation: Ensures the price is a positive number
def validate_price(self, value):
if value <= 0:
raise serializers.ValidationError("Price must be greater than 0.")
return value
views.py
Pro-Tip When writing API views, always use the
Responseobject from DRF instead of Django'sJsonResponse. The DRFResponseis smarter—it can automatically negotiate whether the client wants JSON or another format based on the request headers.
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import Product
from .serializers import ProductSerializer
@api_view(['GET'])
def product_list(request):
"""Fetch all products and return as JSON"""
products = Product.objects.all()
# many=True tells the serializer to handle a list of objects
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
@api_view(['GET'])
def product_detail(request, pk):
"""Fetch a single product by its ID (pk)"""
product = get_object_or_404(Product, pk=pk)
serializer = ProductSerializer(product)
return Response(serializer.data)
Distribute Knowledge
Further Reading

Django DRF - Part 01 - ECommerce Model Architecture
Technical deep dive into modern architecture and development strategies.

🚀 5 Python Concepts You Must Master Before Your First Line of Django
Technical deep dive into modern architecture and development strategies.