The Analogy: A Paper Filing Room in an Accounts Department
Picture the filing room of an old accounts department, before anything was computerised. Along one wall stands a cabinet of green master files, one per client, each holding the client's details and bearing a printed file number. Along the opposite wall stands a second, larger cabinet of manila invoice folders. Every invoice folder is stamped, in the top corner, with the file number of the client it belongs to. That stamped number is the only thing connecting an invoice to its client -- there is no other cross-reference, just the number written on the folder. In Django terms, the master file is a row in a Customer table, the invoice folder is a row in an Invoice table, and the stamped number is a ForeignKey.
The rule that governs this room -- the one pinned to the cabinet door and drilled into every clerk -- is the destruction policy: when a client's master file is pulled out and fed to the shredder, what must the clerk do with all the invoice folders stamped with that client's number? This policy is not decided in the heat of the moment. It is chosen once, written down when the filing system is set up, and applied identically every single time a master file is destroyed. That is exactly what on_delete is: an argument you declare on the ForeignKey at model-design time, and which the ORM then enforces automatically on every delete, without asking again.
The policy has a fixed menu. The clerk may be told to shred every matching invoice folder along with the client (that is CASCADE). Or told to refuse: if any invoice still references the client, the master file may not be shredded at all, and a buzzer sounds (that is PROTECT, and its stricter cousin RESTRICT). Or told to keep each invoice folder but wipe the client-number stamp back to blank -- which only works if the stamp line is allowed to be empty (that is SET_NULL, which requires null=True). Or told to re-stamp each folder with the number of a standing "house account" (that is SET_DEFAULT). Each policy is a deliberate answer to the same question, and each leaves the second cabinet in a different, well-defined state.
Then there is the tempting shortcut, the one a hurried clerk reaches for: shred the master file and touch nothing else (DO_NOTHING). At shred time this is the fastest option and nothing objects. But now dozens of invoice folders carry a client number that indexes an empty slot in the first cabinet. Every audit that follows the number walks to the master cabinet and finds a void. Worse, when a brand-new client is later assigned that same recycled number, they silently inherit a stranger's invoices. Nothing failed at the moment of deletion; the corruption is dormant, and it surfaces only later, when someone actually follows a reference. That is precisely the danger of on_delete=DO_NOTHING: Django removes the parent and leaves the child rows pointing at an id that no longer exists, and unless the database itself carries a constraint, the damage stays invisible until a join or a lookup dereferences the orphan.
Syntax or Core Structure
A model is a Python class whose attributes are field instances; Django maps the class to a table and each field to a column. Here is a small invoicing schema written in real Django, showing field types, a nullable-with-default text field, and a ForeignKey whose on_delete is PROTECT so a customer cannot be deleted out from under their invoices:
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
active = models.BooleanField(default=True)
class Invoice(models.Model):
customer = models.ForeignKey(
Customer, on_delete=models.PROTECT, related_name="invoices"
)
amount_cents = models.PositiveIntegerField()
note = models.CharField(max_length=200, blank=True, default="")
def __str__(self):
return "Invoice #%d" % self.pk
We cannot run a database here, but the part worth seeing run is how a row is built: which fields are required, which fall back to a default, and where validation bites. The plain-Python builder below applies the same rules a model's field definitions imply -- required unless a default exists, and length/sign checks -- so the output is exact:
# Field defaults and validation, reduced to a plain builder.
FIELDS = {
"name": {"type": "char", "max_length": 100},
"amount_cents": {"type": "posint"},
"note": {"type": "char", "max_length": 200, "default": ""},
"active": {"type": "bool", "default": True},
}
def make(**given):
row = {}
for field, spec in FIELDS.items(): # dict keeps insertion order
if field in given:
value = given[field]
elif "default" in spec:
value = spec["default"]
else:
raise ValueError("missing required field: " + field)
if spec["type"] == "char" and len(str(value)) > spec["max_length"]:
raise ValueError(field + " too long")
if spec["type"] == "posint" and (not isinstance(value, int) or value < 0):
raise ValueError(field + " must be a non-negative integer")
row[field] = value
return row
r = make(name="Acme", amount_cents=1500)
print(r["name"], r["amount_cents"], repr(r["note"]), r["active"])
for bad in [dict(amount_cents=100), dict(name="Acme", amount_cents=-5)]:
try:
make(**bad)
except ValueError as ex:
print("error:", ex)
Output:
Acme 1500 '' True
error: missing required field: name
error: amount_cents must be a non-negative integer
The first row fills note from its default of "" and active from True, so only name and amount_cents had to be supplied -- exactly the fields with no default. The second call omits name, and because fields are checked in declaration order the very first required-but-missing field is the one reported. The third supplies a negative amount, which a PositiveIntegerField forbids. Django performs these checks at different moments (full_clean() for validation, the database for constraints), but the shape is the same: defaults fill gaps, and required or malformed values are rejected before the row is stored.
Technical Depth: Field Types, Nullability and on_delete
Three decisions dominate model design: which field type stores each value, whether a value may be absent, and what happens to related rows when a parent is deleted. Each has a table of well-defined options, and getting them right at design time removes whole categories of runtime bug.
Choosing a field type
The field type fixes both the Python value your code sees and the column type in the database. Picking the narrowest type that fits your data lets the database enforce correctness for you.
| Field | Stores | Typical column |
|---|---|---|
| CharField(max_length=n) | short bounded text | varchar(n) |
| TextField | unbounded text | text |
| PositiveIntegerField | whole numbers, zero or more | integer |
| BooleanField | a true or false value | boolean |
| DateTimeField | a point in time | timestamp |
| DecimalField(max_digits, decimal_places) | exact fixed-point numbers | numeric |
| ForeignKey | a link to one row of another table | integer plus a constraint |
null versus blank
These two settings look similar and are constantly confused, but they live on different layers and answer different questions. null is about the database column; blank is about form and validation.
| Setting | Layer it affects | What it means |
|---|---|---|
| null=True | database | the column may hold SQL NULL |
| null=False (default) | database | the column is declared NOT NULL |
| blank=True | validation and forms | the field may be submitted empty |
| blank=False (default) | validation and forms | the field is required in a form |
The practical rule falls out of the table: for text, prefer blank=True with default="" and leave null=False, so an empty string is the single representation of "no text". Adding null=True to a text field creates two distinct empties -- NULL and "" -- that every query then has to handle.
The on_delete menu
Every ForeignKey must declare on_delete; there is no default, because the right answer depends entirely on what the relationship means. The options map one-to-one onto the filing-room policies from the analogy.
| on_delete | When the parent is deleted | Requirement on the child field |
|---|---|---|
| CASCADE | the child rows are deleted too | none |
| PROTECT | the delete is blocked, an error is raised | none |
| RESTRICT | the delete is blocked if referenced | none |
| SET_NULL | the child link is set to NULL | null=True |
| SET_DEFAULT | the child link is set to its default | a default must be set |
| DO_NOTHING | nothing happens; rows may dangle | you enforce integrity yourself |
To see these behave, here is the deletion applied to a small set of invoices under each policy -- a plain function so the resulting rows are exact:
# on_delete, reduced: delete a customer and apply each policy to its invoices.
def has_children(cid, invs):
return any(i["customer"] == cid for i in invs)
def delete_customer(cust_id, policy, invoices):
if policy in ("PROTECT", "RESTRICT") and has_children(cust_id, invoices):
return "blocked: customer still has invoices"
kept = []
for inv in invoices:
if inv["customer"] != cust_id:
kept.append(inv)
elif policy == "CASCADE":
continue # drop the invoice
elif policy == "SET_NULL":
kept.append({**inv, "customer": None})
elif policy == "SET_DEFAULT":
kept.append({**inv, "customer": 0}) # 0 == house account
else: # DO_NOTHING
kept.append(inv) # left dangling
return kept
base = [{"id": 10, "customer": 1}, {"id": 11, "customer": 1}, {"id": 12, "customer": 2}]
print("PROTECT ->", delete_customer(1, "PROTECT", base))
print("CASCADE ->", [i["id"] for i in delete_customer(1, "CASCADE", base)])
print("SET_NULL ->", [(i["id"], i["customer"]) for i in delete_customer(1, "SET_NULL", base)])
print("DANGLING ->", [(i["id"], i["customer"]) for i in delete_customer(1, "DO_NOTHING", base)])
Output:
PROTECT -> blocked: customer still has invoices
CASCADE -> [12]
SET_NULL -> [(10, None), (11, None), (12, 2)]
DANGLING -> [(10, 1), (11, 1), (12, 2)]
Read the four lines as four different worlds after deleting customer 1. PROTECT refuses outright because invoices 10 and 11 still point at customer 1. CASCADE takes them with it, leaving only invoice 12 (customer 2). SET_NULL keeps all three invoices but blanks the link on 10 and 11, so they survive as ownerless rows. DO_NOTHING is the trap: the output looks unchanged, invoices 10 and 11 still read customer 1 -- but customer 1 is gone, so those references now point into a void. Only DANGLING produces silent corruption, and only DANGLING produced no error to warn you.
Real World Example: An Invoicing Schema and What Deletion Does to It
The choice of on_delete is not academic -- it changes how much money your reports say is owed. The program below carries four invoices across two customers, some paid and some not, and reports, for a given deletion policy, how many invoices survive, how many cents remain outstanding, and how many are left orphaned (pointing at no customer). Every figure is a whole number of cents so it can be checked by hand.
invoices = [
{"id": 10, "customer": 1, "cents": 1500, "paid": False},
{"id": 11, "customer": 1, "cents": 500, "paid": True},
{"id": 12, "customer": 2, "cents": 2000, "paid": False},
{"id": 13, "customer": 2, "cents": 750, "paid": False},
]
def outstanding(invs):
return sum(i["cents"] for i in invs if not i["paid"])
def delete_under(cust_id, policy):
children = [i for i in invoices if i["customer"] == cust_id]
if policy == "PROTECT" and children:
return "blocked", invoices
survivors = []
for i in invoices:
if i["customer"] != cust_id:
survivors.append(i)
elif policy == "SET_NULL":
survivors.append({**i, "customer": None})
# CASCADE: append nothing -- the invoice is removed
return "ok", survivors
def report(cust_id, policy):
status, result = delete_under(cust_id, policy)
if status == "blocked":
n = len([i for i in invoices if i["customer"] == cust_id])
return policy + " del " + str(cust_id) + ": blocked (" + str(n) + " invoices)"
orphans = [i for i in result if i["customer"] is None]
return (policy + " del " + str(cust_id) + ": " + str(len(result)) + " invoices left, "
+ str(outstanding(result)) + " cents outstanding, " + str(len(orphans)) + " orphaned")
print(report(1, "PROTECT"))
print(report(1, "CASCADE"))
print(report(1, "SET_NULL"))
print(report(2, "CASCADE"))
Output:
PROTECT del 1: blocked (2 invoices)
CASCADE del 1: 2 invoices left, 2750 cents outstanding, 0 orphaned
SET_NULL del 1: 4 invoices left, 4250 cents outstanding, 2 orphaned
CASCADE del 2: 2 invoices left, 1500 cents outstanding, 0 orphaned
Start with the two customers and their books. Customer 1 holds invoices 10 (1500 cents, unpaid) and 11 (500 cents, paid); customer 2 holds invoices 12 (2000, unpaid) and 13 (750, unpaid). The whole ledger owes 1500 + 2000 + 750 = 4250 cents, since the paid invoice contributes nothing to the outstanding total.
Deleting customer 1 under PROTECT is refused: two invoices still reference them, so nothing changes and the operation reports the block. That is the safe default when the reference must not be lost by accident.
Under CASCADE, deleting customer 1 takes invoices 10 and 11 with it, leaving only customer 2's two invoices and 2750 cents outstanding. Under SET_NULL, all four invoices survive but 10 and 11 become orphans -- their customer link is blank -- so the report shows 4 invoices, the full 4250 cents still outstanding, and 2 orphaned. The last line deletes customer 2 under CASCADE instead, dropping invoices 12 and 13 and leaving customer 1's 1500 outstanding cents.
The code is realistic and also flawed in instructive ways. First, cents is a bare integer with no currency field, so the moment the business bills in two currencies the outstanding total silently adds pounds to yen and means nothing. Second, SET_NULL keeps orphaned invoices in the outstanding total (the 4250 above), yet those amounts are now owed by nobody -- any report grouped by customer will lose them, so the ledger total and the per-customer totals disagree. Third, paid is a boolean, which cannot express a partial payment; a half-paid invoice is either fully outstanding or fully settled, never in between. Fourth, delete_under rebuilds its result from the module-level list and never persists anything, modelling a single request with no transaction -- a real cascade touches many rows and must be atomic, or a crash midway leaves a half-deleted graph that no policy can describe.
Common Mistakes
- Reaching for CASCADE by reflex.
on_delete=models.CASCADEis the option people copy without thinking, and it means "deleting this parent silently deletes all of these children". On aUserforeign key that can wipe every order, comment, and invoice the moment an account is removed. Choose CASCADE only when the child genuinely cannot exist without the parent.
- Putting null=True on a text field. A
CharFieldorTextFieldwithnull=Truecan now be empty two different ways -- SQL NULL or the empty string -- and every filter, template, and comparison must handle both. Useblank=Truewithdefault=""instead and keep the column NOT NULL.
- Storing money as a float.
FloatFieldcannot represent 0.10 exactly, so sums drift by fractions of a cent and reconciliations fail. UseDecimalField(max_digits, decimal_places)or store integer minor units (cents) as this lesson does.
- Using a mutable literal as a default.
default=[]ordefault={}evaluates once and is shared across every instance, so appending to one row's list mutates them all. Pass a callable instead --default=list,default=dict, or a named function.
- Adding a required column to a populated table. A new
NOT NULLfield with no default cannot be applied to existing rows, so the migration either refuses to run or prompts for a one-off value. Add the field with a default (or in two steps) when the table already has data.
- Omitting related_name on foreign keys. Without it you address the reverse relation as
invoice_set, and two foreign keys from the same model to the same target collide outright. Setrelated_name="invoices"so the reverse accessor reads clearly and never clashes.
- Guessing max_length or misusing CharField. A
max_lengthplucked from the air truncates real data, and usingCharFieldfor genuinely unbounded text forces an arbitrary cap. Size bounded fields to the real domain and useTextFieldwhen there is no natural limit.
- Leaving a fixed set as free text. Storing a status as an unconstrained string invites "paid", "Paid", and "PAID" to coexist. Use
choices(or aTextChoicesclass) so the allowed values are defined in one place and validated on save.
- Choosing DO_NOTHING without a database constraint.
DO_NOTHINGtells Django to skip cleanup entirely; unless the database has its own cascade or restrict rule, you are left with child rows pointing at a deleted parent. Reserve it for cases where the database enforces integrity itself, and never as a shortcut.
Best Practices
- Decide on_delete per relationship and record why. Ask "if the parent vanishes, what should happen to this child?" for every foreign key, and let the answer -- not habit -- pick the option. A one-line comment saving the reasoning pays for itself at the next schema review.
- Prefer PROTECT for references you must not lose silently. When accidental deletion would destroy data you care about, PROTECT turns a silent cascade into a loud error you can handle. Save CASCADE for true ownership, where the child is meaningless without the parent.
- Store money as integer minor units or DecimalField. Never use a float for currency. Keeping cents as integers (or using DecimalField) makes every total exact and every comparison reliable.
- Model optional text as blank plus an empty-string default. Use
blank=True, default=""and leavenull=Falseso "no value" has exactly one representation, keeping queries and templates simple.
- Use choices for any fixed set of values. A
TextChoicesclass gives you validation, readable labels, and a single source of truth, replacing scattered magic strings that drift out of sync.
- Give every foreign key a related_name. An explicit reverse name makes queries self-documenting (
customer.invoices.all()) and prevents clashes when a model points at the same target twice.
- Use callables for dynamic or mutable defaults.
default=list,default=dict, anddefault=timezone.noware evaluated per row, avoiding the shared-mutable-state trap and giving each instance its own value.
- Keep row behaviour on the model. Put derived values and rules (
is_overdue,total_with_tax) on the model as methods or properties, and complex queries on a custom manager, so logic lives with the data instead of scattering through views.
Practice Exercises
- Design an Invoice model. Write a Django
Invoicewith a customer foreign key, a currency amount, an issue date, and an optional cancellation reason. Choose anon_deletefor the customer link and justify it explicitly against the two alternatives you rejected, saying what each would do when a customer is deleted.
- Extend the on_delete stand-in. Add
RESTRICTandSET_DEFAULT(house account 0) branches to thedelete_customerfunction, then hand-trace deleting customer 1 for both policies over thebaselist and give the exact returned value for each.
- Trace two more reports. Using the Real World program, work out the output of
report(2, "SET_NULL")andreport(2, "PROTECT")by hand, showing the invoices left, cents outstanding, and orphan count for each.
- Fix the flaws. Redesign the invoicing schema to support partial payments and more than one currency. List the new or changed fields, and state which of the four named flaws each change addresses.