×
Chapter 7
Excerpt
Libraries
Which libraries should you actually know?
You're reading an excerpt: the introduction to section 7.1 and 7.1.1 django . The full chapter is in the ebook.
7.1 Web & API frameworks
This is overwhelmingly backend territory, with a secondary presence in QA (where automation engineers need to recognize the frameworks they're testing against).
7.1.1 django
Core for: BE · Also relevant for: QA
In interviews: The ORM is one of the most likely deep-dive areas. Expect questions like "what's the difference between filter and get?" , "what does on_delete=CASCADE do?" , and something about querysets being lazy. The MTV architecture and the request/response cycle are the usual conceptual warm-ups. If the role uses Django REST Framework, that's typically its own separate deep-dive.
On the job: you'll live in models and views. You define your data, query it, and turn the results into responses. The framework does a surprising amount for you, so the early skill is learning what is already handled (auth, the admin, migrations, the ORM) and not rebuilding it by hand.
7.1.1.1 What and why
Suppose you're putting a bank online. A customer—call him Jeff—types mybank.com/accounts/42 into his browser, and a second later he's looking at his account page: the balance, the recent transactions. Strip down what had to happen in that second and you find many related but separate activities. Something had to recognize that /accounts/42 means "the detail page for Jeff's account" and hand it to the right chunk of code. That code had to go into the database, find Jeff's account, and pull out its balance and transactions. Something had to check that Jeff is logged in and actually allowed to see that account—which means somewhere passwords are being hashed, a login form exists, and the submitted data is being validated. And so that your staff aren't editing raw database rows by hand, something has to generate a back-office screen too.
You could assemble every one of those pieces yourself from smaller libraries—that's what micro-frameworks like Flask and FastAPI (both later in this chapter) expect you to do. Django takes the opposite bet: it ships the whole stack in the box—an ORM, an admin interface, an authentication system, forms, templating, migrations—and asks only one thing in return, that you organize the project its way rather than yours.
So how does Django get from /accounts/42 to that finished page? Four parts pass the work along, each with one job.
urls.py decides who handles the request. It holds a list of URL patterns and goes down that list, comparing each one to the incoming address until it finds the pattern that fits. When /accounts/42 matches, it hands the request to the one view responsible for that page.
The view does the work. It's the chunk of code that takes the request and figures out what's needed. For Jeff's account, that means going and getting the account's data—but the view doesn't talk to the database directly.
The models fetch the data. Models are your database tables (more on them in a moment). The view asks them for Jeff's account, and they hand back its balance and transactions.
The template decides how it looks. It's an HTML page with blanks left in it. The view drops Jeff's account data into those blanks, and the filled-in page goes back to the browser as the response.
URL → view → model → template → response. Django's name for this structure is MTV : Model, Template, View.
A Django view is not the visual part. It plays the role most other frameworks give to a controller —the code that handles the request and decides what to do. (Django's own documentation pushes back on that label, but it's the comparison interviewers expect, and it's the right mental map.) The visual layer is actually the template .
The biggest thing Django gives you is the ORM —the Object-Relational Mapper. Here's the problem it solves: you think in Python objects, but the database only understands SQL. The ORM is the translator sitting between the two. Say you want every account with a balance over $1,000. You write it in Python:
Account.objects.filter(balance__gt=1000)
and the translator turns that into SQL along these lines—
SELECT * FROM accounts WHERE balance > 1000;
—which just means pull every row from the accounts table where the balance is over 1,000 . (The SQL Django actually generates is wordier—it prefixes the table name with your app's name, like bank_account, and lists every column instead of *—but this is the shape of it.)
The ORM runs that and hands the matching rows back to you as Account objects. The ORM also accounts for a large share of the most-used names in the counts below, so that's where we'll spend most of our time.
Most-used names (✓ = covered in this section):
reverse path objects db Q filter CASCADE name render get user override_settings ValidationError client redirect get_for_model SET_NULL get_object_or_404 status_code
7.1.1.2 Models—your data as Python classes
A model is a Python class that maps to a database table. Each class attribute is a column, and each row in the table is one instance of that class. You describe your data once, in Python, and Django builds and manages the underlying table for you.
from django.db import models
class Customer(models.Model): # → a customer table
name = models.CharField(max_length=100) # a text column, up to 100 chars
email = models.EmailField() # a text column, validated as an email
class Account(models.Model): # → an account table
customer = models.ForeignKey( # a column linking each account
Customer, on_delete=models.CASCADE) # to one Customer row (see 7.1.1.3)
balance = models.DecimalField( # a numeric column
max_digits=12, decimal_places=2)
opened = models.DateField() # a date column
So the Customer class is the customer table; name and email are two of its columns; and saving a Customer(name="Jeff", ...) writes one row into it. (If you go looking for the table itself, remember the naming rule from above: in an app called bank, the table is bank_customer.)
A model is only a description until Django builds the matching table—editing the model changes the database no more than drawing a new wall on a blueprint moves any bricks. Two commands bridge that gap. makemigrations reads your model changes and writes them up as a work order—a migration file describing exactly what should change. migrate then sends in the builders to apply that work order to the real database. Beginners edit the model, see no change in the database, and get confused.
7.1.1.3 ForeignKey and on_delete
A ForeignKey is how one record points at another. A single transaction means nothing on its own—a $50 withdrawal has to be a withdrawal from someone's account. So every transaction row stores a reference back to the account it belongs to, exactly the way each line on a paper statement sits underneath one account number. That stored reference is the ForeignKey.
But not every row that points at an account carries the same weight. A transfer Jeff started and never confirmed is disposable—if he closes the account tomorrow, that draft should simply go. A posted transaction is the opposite: it's the account's actual history, and it must never quietly disappear just because someone deleted the account it belonged to.
class PendingTransfer(models.Model):
# a transfer started but never confirmed
account = models.ForeignKey(
# delete the account → unconfirmed drafts go too
Account, on_delete=models.CASCADE)
amount = models.DecimalField(max_digits=12, decimal_places=2)
class Transaction(models.Model):
# a completed, posted transaction
account = models.ForeignKey(
# refuse to delete an account with real history
Account, on_delete=models.PROTECT)
amount = models.DecimalField(max_digits=12, decimal_places=2)
# each transaction is tagged with a category
category = models.ForeignKey(
# delete the category → transaction survives,
"Category", on_delete=models.SET_NULL,
# its link just goes empty (hence null=True)
null=True)
class Category(models.Model):
name = models.CharField(max_length=50) # → a category table
ForeignKey and on_delete are a staple of Django interviews. The on_delete argument is mandatory, because the database forces you to answer an awkward question up front: when the thing on the other end is deleted, what happens to this row? Three answers cover almost everything you'll meet, and the models above put each one where it actually belongs:
CASCADE —delete the account, and its unconfirmed drafts go with it. A PendingTransfer that was never confirmed has no meaning on its own. The deletion cascades down the link.
PROTECT —refuse the deletion outright. A posted Transaction is exactly the kind of row you must never lose silently—real financial systems essentially never let you delete an account that has transaction history, and PROTECT is how you enforce that at the database layer. Try it anyway and Django raises ProtectedError instead of quietly destroying records.
SET_NULL —the child survives, but its link is set to NULL. This fits a different relationship. Each transaction is also tagged with a spending category; delete the "Groceries" category and you don't want every grocery transaction to vanish—you just want them to become uncategorized. SET_NULL orphans the child instead of killing it. It requires null=True on the field, since the column now has to be allowed to be empty.
CASCADE is for rows that only exist as an extension of their parent and have no standalone value; PROTECT is for rows that must survive no matter what happens upstream; SET_NULL is for links that are convenient but disposable. (In a real bank you'd almost never call .delete() on an Account at all—you'd mark it closed and keep it forever. PROTECT is what stands in the way if someone tries anyway.)
There's also SET_DEFAULT and DO_NOTHING, and you'll meet them far less often. (CASCADE and SET_NULL both appear in the frequency list at the top of this section; PROTECT doesn't—but it's the correct real-world choice for this relationship, so it earns its place regardless.) The expected interview answer: CASCADE deletes the children, PROTECT refuses, SET_NULL orphans the child without deleting it.
7.1.1.4 Querying—objects, filter, and get
Every model has an objects attribute, called its manager . It's the starting point for every query: to read rows from the table, you go through objects first:
Account.objects.all() # every account
Account.objects.filter(balance__gt=1000) # a QuerySet: zero or more matches
Account.objects.get(pk=1) # one row, or it raises an exception
The filter vs get distinction is one of the most common ORM questions. filter asks "show me all the accounts matching this"—you get back a QuerySet , a collection that might hold zero, one, or a thousand rows. get asks for one specific row, the way you'd look someone up by a unique passport number: you expect exactly one human to come back, so get is strict about it. Nobody matches? It raises Model.DoesNotExist. Two rows somehow match? It raises Model.MultipleObjectsReturned. Rule of thumb: reach for get only when you expect exactly one result (a lookup by primary key is the classic case), and filter for everything else.
Two more things to know.
First, querysets are lazy. Writing Account.objects.filter(...) doesn't touch the database—the translator just notes down what you asked for and waits. You can keep adding to the request, .filter().exclude().order_by(), and each step only amends the note. The query runs only when you actually force a result: when you loop over the queryset, wrap it in list(), ask len() for its size, pull out a single item by index, or test it in an if. (One thing that does not run it, despite how it looks: plain slicing. accounts[:10] just hands you another lazy queryset with a limit attached.)
Why hold off? Because by waiting until the data is genuinely needed, Django gets to see your entire request before it runs anything. It folds the whole chain into a single SQL statement, and the database's own query planner then works out the fastest way to fetch it. Think of it as the difference between two ways of shopping. The first way: you run to the shop at the exact moment each item pops into your head—ten items, ten separate trips. The second way: you write the full list first. Now you can see everything at once and plan a single efficient route.
But lazy doesn't mean cheap, and the classic trap is the N+1 problem . Stay with the shopping picture. You make one trip and bring home all 100 accounts—so far so good. But then, for each account, you reach for account.customer.name. That customer's name was never in your basket, so off you go back to the shop to fetch it—and you do this once for every single account . One sensible trip for the accounts, then 100 more trips for the 100 customers: 101 trips where 2 would have done. The fix is to put the customers on the original list, and Django gives you two tools for it. select_related tells the translator "grab each account's customer while you're there"—everything comes home in a single trip (one combined SQL query). prefetch_related works a little differently: it makes one extra trip that picks up all the customers at once, then matches them up at home—two trips total, which is the best you can do for many-to-many relationships. You don't need to wield either one yet, but be able to say "N+1," explain it as those extra trips, and name the two fixes.
Second, the double-underscore (__) syntax does two jobs. The first is saying how to compare—not just "equals," but "greater than," "in this year," and so on: balance__gt=1000 means balance greater than 1000, and opened__year=2020 means opened during 2020. The second is hopping from one table to a related one: customer__name="Smith" starts at an account, follows its ForeignKey across to the customer, and filters on the customer's name.
7.1.1.5 Q—OR and complex conditions
Ordinary filter arguments are combined with AND . filter(a=1, b=2) means "both." The moment you need OR , or a negation, plain keyword arguments can't express it. That's what Q objects are for, and why Q sits so high in the counts: it's the standard way to write anything beyond a plain AND.
from django.db.models import Q
# accounts to review: either overdrawn OR holding a suspiciously large balance
Account.objects.filter(Q(balance__lt=0) | Q(balance__gt=1_000_000))
| is OR, & is AND, and ~ is NOT. You can also build a Q up step by step in code and pass it in, which is how dynamic search filters get assembled.
7.1.1.6 URLs—path and reverse
reverse is the most-used name in our Django sample. First, the routing side: path defines which URL maps to which view, and gives each route a name (that's the high-ranking name attribute):
from django.urls import path
from . import views
urlpatterns = [
# /accounts/ → list view
path("accounts/", views.account_list, name="account-list"),
# /accounts/42/ → detail view
path("accounts/<int:pk>/", views.account_detail, name="account-detail"),
]
The <int:pk> part captures a piece of the URL—the 42 in /accounts/42/—and passes it to the view as an argument. Now the other direction: reverse turns a route's name back into its actual URL string.
from django.urls import reverse
reverse("account-detail", args=[42]) # "/accounts/42/"
reverse tops the list because of the rule behind it: never hard-code URLs. If you scatter "/accounts/42/" literals through your views, templates, and tests, then changing that URL pattern later breaks all of them silently. Instead you refer to the name , and reverse (or its template twin, the {% url %} tag) computes the real path. Change the pattern once, and every link follows. Think of it as a phone book: you look people up by name, so you never have to memorize or update the numbers. You'll also meet reverse_lazy for places that run at import time, such as a class-based view's success_url, where the URL config isn't loaded yet.
7.1.1.7 Views—render, redirect, get_object_or_404
A view takes a request and returns a response. Three shortcuts from django.shortcuts cover most of what a view does:
from django.shortcuts import render, redirect, get_object_or_404
def account_detail(request, pk):
account = get_object_or_404(Account, pk=pk) # fetch it, or 404
return render(request, "accounts/detail.html",
{"account": account}) # template + context → HttpResponse
def account_create(request):
# ... validate and save the new account ...
return redirect("account-detail", pk=account.pk) # send the browser onward
render is the workhorse. It loads a template, fills it with a context dict, and returns the rendered result as an HttpResponse . redirect sends the browser to another URL, and it takes a route name , leaning on reverse under the hood. get_object_or_404 does a get, but if the object doesn't exist it raises an Http404 instead of a DoesNotExist exception, which turns into a clean "404 Not Found" page. It saves you from writing try: ... except Account.DoesNotExist: ... in every detail view.
The user attribute shows up here too. request.user is the currently logged-in user (an instance of the User model, or an AnonymousUser if nobody is logged in). You'll guard views with request.user.is_authenticated constantly.
Two more request attributes you'll reach for all the time:
request.GET holds query-string parameters (the part after ? in a URL).
request.POST holds submitted form data.
Both are dictionary-like objects called QueryDicts—close enough to a dict for daily use (.get("key") behaves as you'd expect), but worth knowing they can hold multiple values under one key and are normally immutable during request handling. Reach for .getlist("key") when a field can legitimately appear more than once, such as a multi-select form input.
7.1.1.8 The recognize-it tier
These names appear often in real code, but a junior meets them mostly by reading code rather than writing it.
Validation. ValidationError is what Django raises when a value fails a form or field check. You'll see it in custom form-cleaning methods, e.g. raise ValidationError("Must be a business email."). Django catches it, attaches the message to the right field, and re-renders the form with the error shown. You rarely wire that up yourself early on.
Testing. Django's testing story is strong, and a lot of real Django code is tests—which is why test names rank so high. The two to know: the test client (self.client.get("/accounts/")) simulates HTTP requests without a running server, and status_code is how you check the response came back as expected (self.assertEqual(response.status_code, 200)). You'll also see override_settings , a decorator that changes one setting for a single test and restores it afterward.
The generic stuff. get_for_model (as in ContentType.objects.get_for_model(Account)) belongs to Django's contenttypes framework, which lets Django refer to "a model class" generically. You'll meet it indirectly, through permissions and the admin.
Configured once, not called repeatedly. Several major Django pieces don't rack up function-call counts because you set them up once: the admin site (a full CRUD interface—create, read, update, delete—that Django generates from your models; one line to register each model, and the "back-office screen" from the opener exists), templates , middleware , and settings.py . They're central to working in Django even so. And for building APIs rather than HTML pages, most teams add Django REST Framework on top—a topic large enough to warrant its own study.
7.1.1.9 The pieces at a glance
7.1.1.10 Minimum viable checkpoint
What's the difference between Account.objects.filter(...) and Account.objects.get(...), and what does get do when zero or two rows match?
Explain on_delete=CASCADE, on_delete=PROTECT, and on_delete=SET_NULL—what real situation does each one fit?
Why is hard-coding "/accounts/42/" in your code a bad idea, and what do you use instead?
What does it mean that a Django QuerySet is "lazy"—and what is the N+1 problem?
When do you need a Q object instead of plain keyword arguments to filter?
What does get_object_or_404(Account, pk=pk) save you from writing by hand?
End of excerpt
Get the full Libraries chapter
The rest of Chapter 7 covers FastAPI, Flask, pydantic, pandas, pytest, and the other libraries that define each target role.
Buy the ebook · $35
14-day refund, no questions asked
Secure checkout via Gumroad