CS Fundamentals Trainer · Guides

Django in practice: models, the ORM, views, Django REST Framework and the traps

How a Django project is put together and where the time goes: models and migrations, lazy QuerySets and the N+1 problem (select_related and prefetch_related), transactions and locking, views and Django REST Framework (serializers, viewsets, permissions, pagination), authentication and CSRF for a React frontend, settings for production, testing, and background work.

9 min read

Django is a "batteries included" web framework: an ORM, migrations, an admin site, authentication, forms, templates and security middleware all come in the box. Most teams that pair it with a React frontend use it as an API server with Django REST Framework (DRF). This guide follows a request from the URL to the database and back, and stops at each place where real projects get slow or wrong.

How a project is organised

A project holds settings, the root URL configuration and the WSGI/ASGI entry points. It is made of apps: packages with their own models, views, URLs, admin registrations and tests (orders, accounts, listings). Apps should be cohesive and depend on each other in one direction; a "common" or "core" app that everything imports from is fine, two apps that import each other's models are a smell.

A request goes through: the middleware stack (security headers, sessions, CSRF, authentication), URL routing (urls.py maps a path to a view), the view (a function or class that returns a response), and back out through middleware in reverse order.

# listings/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("listings/<int:pk>/", views.listing_detail, name="listing-detail"),
]

Models and migrations

A model is a class whose fields map to columns. Django adds an integer (or BigAutoField) primary key unless you declare one.

from django.db import models

class Listing(models.Model):
    title = models.CharField(max_length=200)
    price_cents = models.PositiveIntegerField()
    city = models.CharField(max_length=100, db_index=True)
    owner = models.ForeignKey("accounts.User", on_delete=models.CASCADE, related_name="listings")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [models.Index(fields=["city", "-created_at"])]
        constraints = [models.CheckConstraint(condition=models.Q(price_cents__gt=0), name="price_positive")]

(In Django versions before 5.1 the CheckConstraint argument is called check instead of condition.)

QuerySets are lazy

Listing.objects.filter(city="Recife") does not touch the database. It builds a QuerySet that runs when you iterate it, slice it with a step, call len(), list(), bool(), or evaluate it in a template. Each further .filter(), .exclude() or .order_by() returns a new QuerySet.

Consequences:

The N+1 problem

The classic Django performance bug: list objects and then touch a related object for each one.

for listing in Listing.objects.all():   # 1 query
    print(listing.owner.email)          # +1 query per listing

Two tools fix it:

Find the problem before users do: install django-debug-toolbar in development, log SQL in tests, or assert the count with self.assertNumQueries(2) around a view call. In DRF the N+1 usually hides in a nested serializer, so the fix goes in the view's get_queryset().

Doing work in the database

Transactions and concurrency

By default Django runs in autocommit: each query commits on its own. Group changes that must succeed together with transaction.atomic():

from django.db import transaction

with transaction.atomic():
    booking = Booking.objects.create(room=room, guest=user, nights=3)
    Payment.objects.create(booking=booking, amount_cents=total)

An exception inside the block rolls everything back. Setting ATOMIC_REQUESTS = True wraps each request in a transaction, which is simple but holds the transaction for the whole view.

To stop two requests from booking the same room, lock the row (select_for_update() inside atomic()), or rely on a unique or exclusion constraint in the database and handle IntegrityError. Constraints are the safer last line of defence. Code that must run only after a commit succeeds, such as sending an email or enqueueing a Celery task, goes in transaction.on_commit(lambda: ...), otherwise a worker may look for a row that was rolled back.

Views

Django supports function-based views (a function that takes a request and returns a response) and class-based views (ListView, DetailView, ...). Class-based views reduce repetition but hide control flow in mixins; function-based views are explicit. Teams usually choose by readability.

Keep views thin: parse input, call a function or a service method that holds the business rule, return a response. Business rules in models or services are testable without HTTP.

Django REST Framework

DRF adds the pieces an API needs:

class ListingViewSet(viewsets.ModelViewSet):
    serializer_class = ListingSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]

    def get_queryset(self):
        return Listing.objects.select_related("owner").prefetch_related("photos").order_by("-created_at")

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)   # never trust an owner sent by the client

Return consistent errors: DRF formats validation errors as {"field": ["message"]}. Decide once how the React client reads them and keep to it.

Authentication with a React frontend

Two common setups:

  1. Same site, session cookies. React is served from the same domain (or a subdomain behind the same site). Django's session cookie authenticates requests, and CSRF protection applies: the client reads the csrftoken cookie and sends it in the X-CSRFToken header on unsafe methods. Cookies are HttpOnly, Secure and SameSite=Lax. This is the simplest secure option.
  2. Tokens. DRF's token auth, or JWT with djangorestframework-simplejwt, sent in an Authorization: Bearer header. No CSRF risk because the browser does not attach the header by itself, but the token must be stored somewhere: localStorage is readable by any script on the page, so an XSS bug steals it. Keep access tokens short-lived and refresh tokens revocable.

If the frontend is on another origin, configure CORS with django-cors-headers: an explicit list of allowed origins, and CORS_ALLOW_CREDENTIALS = True only when cookies are needed. Never use a wildcard origin with credentials.

Use a custom user model (AUTH_USER_MODEL) from the first migration of a new project; switching later is painful.

Settings for production

python manage.py check --deploy lists the important ones. The essentials:

Read settings from environment variables (django-environ or plain os.environ) so the same image runs in every environment.

Testing

Background work and async

Slow work (emails, image processing, calls to other services) leaves the request: a task queue such as Celery (with Redis or RabbitMQ), RQ or Dramatiq, enqueued from transaction.on_commit. Tasks must be idempotent, because brokers deliver at least once.

Django supports async def views under ASGI, and the ORM offers async methods (await Listing.objects.aget(pk=1), async for over a QuerySet), but database access still runs in a thread underneath, and many third-party packages are synchronous. Use async views for many concurrent waits on I/O (calls to other APIs, long polling), not to speed up ordinary CRUD.

Signals, the admin and other features

A checklist for reviews

  1. Does any list view or serializer touch a relation without select_related/prefetch_related?
  2. Are multi-step writes inside transaction.atomic(), and are invariants backed by constraints?
  3. Is every queryset filtered by what the user may see, not only checked with a permission class?
  4. Are side effects deferred with on_commit, and are tasks idempotent?
  5. Are migrations safe to run while the old code is still serving traffic?
  6. Are DEBUG, ALLOWED_HOSTS, cookie and HSTS settings right for production (check --deploy)?

Sources

Practise this topic: Python Python › Web

More guides