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.)
python manage.py makemigrationscompares the models with the migration history and writes a new migration file;migrateapplies pending ones. Commit migration files and review them like code.- Keep migrations backwards compatible with the running code during a deploy: add a nullable column first, deploy, backfill, then make it required. A rename is a drop and an add for the old code.
- Large tables: adding an index locks writes in PostgreSQL unless you use
AddIndexConcurrently(fromdjango.contrib.postgres.operations) in a non-atomic migration. - Data migrations (
RunPython) must useapps.get_model(...), not imported model classes, so they run against the historical schema. - Money is stored as integers (cents) or
DecimalField, neverFloatField.
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:
- A QuerySet caches its results after the first full iteration, but a new QuerySet derived from it runs a new query.
if qs:evaluates the whole QuerySet. Useqs.exists()when you only need to know whether there is a row, andqs.count()for a number.- Slicing (
qs[:20]) becomesLIMIT 20; it is how pagination works.
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:
select_related("owner")follows foreign keys and one-to-one relations with a SQLJOIN, in the same query.prefetch_related("photos")handles reverse foreign keys and many-to-many relations with one extra query per relation (WHERE listing_id IN (...)) and joins the results in Python. APrefetch("photos", queryset=Photo.objects.filter(is_cover=True))object narrows what is fetched.
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
only()anddefer()load fewer columns;values()/values_list()return dicts or tuples without building model objects.F()expressions refer to a column in the database:Listing.objects.filter(pk=pk).update(views=F("views") + 1)increments atomically, without the read-modify-write race ofobj.views += 1; obj.save().Q()objects combine conditions with|,&and~.annotate()andaggregate()withCount,Sum,Avgpush grouping into SQL;SubqueryandExistscover correlated queries.bulk_create()andbulk_update()write many rows in a few queries, but skipsave()and signals.iterator()streams a huge result set instead of caching it all.
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:
- Serializers convert model instances to JSON and validate incoming data. A
ModelSerializerderives fields from a model;validate_<field>()andvalidate()hold custom rules;read_only_fieldsstops clients from settingownerorid. - Views and viewsets:
APIViewfor full control, generic views (ListCreateAPIView), orModelViewSetwith a router that generates the list, create, retrieve, update and delete routes. - Permissions:
IsAuthenticated,IsAdminUser, or custom classes withhas_permissionandhas_object_permission. Object-level rules (only the owner may edit) still need the queryset to be filtered, otherwise a list endpoint leaks rows. - Pagination:
PageNumberPagination,LimitOffsetPaginationorCursorPagination(stable under inserts, good for feeds). - Throttling: per-user or per-anonymous rate limits.
- Filtering: django-filter integrates with viewsets for query parameters.
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:
- 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
csrftokencookie and sends it in theX-CSRFTokenheader on unsafe methods. Cookies areHttpOnly,SecureandSameSite=Lax. This is the simplest secure option. - Tokens. DRF's token auth, or JWT with djangorestframework-simplejwt, sent in an
Authorization: Bearerheader. No CSRF risk because the browser does not attach the header by itself, but the token must be stored somewhere:localStorageis 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:
DEBUG = False(debug pages leak settings and code), a secretSECRET_KEYfrom the environment, and an explicitALLOWED_HOSTS.SECURE_SSL_REDIRECT,SESSION_COOKIE_SECURE,CSRF_COOKIE_SECURE,SECURE_HSTS_SECONDS, andSECURE_PROXY_SSL_HEADERwhen behind a load balancer that terminates TLS.CONN_MAX_AGE(persistent connections) or a pooler such as PgBouncer; each worker process opens its own connections.- Static files collected with
collectstaticand served by WhiteNoise, a CDN or S3, not by Django itself. User uploads go to object storage (django-storages with S3). - Run under a production server: Gunicorn (WSGI) or Uvicorn/Daphne (ASGI). The number of worker processes, not threads, usually limits throughput for CPU-bound views.
Read settings from environment variables (django-environ or plain os.environ) so the same image runs in every environment.
Testing
django.test.TestCasewraps each test in a transaction and rolls it back, which keeps tests fast and isolated.TransactionTestCasetruncates tables instead and is needed when the code under test relies on commits (for exampleon_commithooks, thoughTestCase.captureOnCommitCallbacks()covers most of those).- DRF's
APIClient(client.force_authenticate(user)) calls views through the full stack. - pytest-django gives pytest fixtures (
db,client,django_assert_num_queries), and factory_boy builds test objects without long fixtures. - Test the rules (permissions, validation, concurrency), not the framework.
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
- Signals (
post_save, ...) decouple code but hide control flow and do not fire forupdate()orbulk_create(). Prefer an explicit call in a service function unless you really need the hook. - The admin is a productive internal tool. Restrict it to staff, add
list_select_relatedandraw_id_fieldson large tables so its pages do not run thousands of queries, and do not expose it as a customer feature. - Caching: the cache framework works with Redis or Memcached; per-view caching (
cache_page) and low-levelcache.get_or_set()are the usual tools, and you need to decide how entries are invalidated.
A checklist for reviews
- Does any list view or serializer touch a relation without
select_related/prefetch_related? - Are multi-step writes inside
transaction.atomic(), and are invariants backed by constraints? - Is every queryset filtered by what the user may see, not only checked with a permission class?
- Are side effects deferred with
on_commit, and are tasks idempotent? - Are migrations safe to run while the old code is still serving traffic?
- Are
DEBUG,ALLOWED_HOSTS, cookie and HSTS settings right for production (check --deploy)?
Sources
- Django documentation: models, QuerySets, transactions, migrations, deployment checklist.
- Django: Database access optimization.
- Django REST Framework documentation.
- Django: Cross Site Request Forgery protection and django-cors-headers.
- pytest-django.
Practise this topic: Python Python › Web