Python offers two excellent backend frameworks: Django (batteries‑included)
and FastAPI (modern, async, OpenAPI). This tutorial covers both, helping
you choose the right tool for the job. You'll build models, serializers,
views, and migrations.
Why this matters:
Python is one of the most popular backend languages. Knowing both Django
and FastAPI makes you versatile and ready for different types of projects.
# products/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
Serializer
# products/serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'price', 'created_at']
ViewSet
# products/views.py
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
# myapi/urls.py
from rest_framework.routers import DefaultRouter
from products.views import ProductViewSet
router = DefaultRouter()
router.register('products', ProductViewSet)
urlpatterns = router.urls
2. FastAPI
Setup
pip install fastapi uvicorn
App with SQLAlchemy
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
app = FastAPI()
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String)
price = Column(Float)
class ProductSchema(BaseModel):
name: str
price: float
# Dependency: get_db()
pip install alembic
alembic init -t async alembic
# Edit alembic/env.py for async support
alembic revision --autogenerate -m "create products table"
alembic upgrade head
4. Serializers & Schemas
Serializers (Django) and Pydantic schemas (FastAPI) validate and transform data.
FastAPI Pydantic Example
from pydantic import BaseModel, Field
from datetime import datetime
class ProductCreate(BaseModel):
name: str = Field(..., min_length=2, max_length=100)
price: float = Field(..., gt=0)
class ProductResponse(ProductCreate):
id: int
created_at: datetime
Quiz
Question 1
Which Django component defines the data structure?
View
Model
Serializer
URL
Show answer
B. Model.
Question 2
Which FastAPI library is used for data validation?
SQLAlchemy
Pydantic
Django ORM
Marshmallow
Show answer
B. Pydantic.
Question 3
What command creates migrations in Django?
python manage.py migrate
python manage.py makemigrations
python manage.py create
python manage.py db
Show answer
B. python manage.py makemigrations.
Exercises
Exercise 1
Create a Django model for a Category with name and description
fields.
Sample answer
class Category(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True)
def __str__(self):
return self.name
Exercise 2
Write a FastAPI endpoint that returns a list of products with a
status field (success/error).
You explored Python's two leading backend frameworks: Django (full‑featured)
and FastAPI (modern, async). You built models, migrations, serializers/schemas,
and endpoints. You now understand the strengths of each framework and when
to choose one over the other.
Key takeaway: Django is ideal for monolithic applications
with built‑in admin and ORM. FastAPI is perfect for microservices and
async‑heavy workloads with automatic OpenAPI documentation.