Designing Objects in Django
In this pack: sizing and rule strictness are set by the core
plugin's oo-design skill; each rule here keeps a core rule in this
language.
Overview
This skill holds only what Django changes on top of oo-python: load
that skill too, because its rules on protocols, frozen dataclasses and
state kept behind its class still hold in a Django code base. Django
supplies an object-relational mapper whose model classes stand for
rows and save themselves, forms and views at the edge, signal receivers
that run when a model is saved, and apps that may import each other's
models. Each of those offers a place to keep a decision that belongs to
the domain: a clean() method that save() never runs, a view that
sets a guarded field, a bulk update that writes behind every model
method, a signal receiver that holds a reaction, and apps that import
each other's models until no boundary is left. Django 6.1 on Python
3.12 or later changes where these rules are kept, not what they
require.
When to use
- A rule that guards a status change sits in
clean(), a view or a
form, and a save() path reaches the field without it.
- A view, a management command or a script changes a guarded field with
QuerySet.update(), bulk_update() or bulk_create().
- A
pre_save or post_save receiver writes another model, sends to
another system, or holds a rule.
- A view or a form decides whether a change is allowed, or one request
opens several saves.
- Two apps import each other's models, or one app reads another app's
table as its own.
- A filter chain is repeated in views instead of named on a manager or
a
QuerySet.
When not to use
- The code is plain Python that imports nothing from Django, which
oo-python covers.
- The question is how a template or a front-end component splits its
state from the domain: outside this skill, and
oo-separating-presentation-from-domain covers the core rule.
- A question no Django feature changes, such as which object owns a
rule: the core skills, starting from
oo-design.
Core rules
Rule. Keep a rule that guards a state change in a model method
named for the action, which takes the time it needs as a parameter
and checks before it changes anything, because save() never runs
full_clean(), so a rule that lives only in clean() holds only
for forms, as oo-working-within-a-framework rule 1,
oo-encapsulating-state-and-behaviour rules 1 and 3,
oo-designing-failure-behaviour rule 4 and
oo-designing-for-testability rule 3 ask. save() runs neither
full_clean() nor clean(), the hook for validation that needs more
than one field; a ModelForm runs the model's validation for the
fields the form holds, so a rule in clean() refuses a form's
invalid input and lets a script, a view that assigns a field, or a
bulk write past it. A model method such as schedule(now) reads the
current state, refuses the call in the clinic's words before it
assigns anything, and writes only when the rule holds; the time it
decides with arrives as a parameter, so a test passes the time it
chooses.
Rule. Never change state that a rule guards with
QuerySet.update(), bulk_update() or bulk_create(), which call
no save() and send no pre_save or post_save, as
oo-designing-repositories rule 6 asks. update() runs an SQL
update for the rows it matches, bulk_update() saves its changes
through the same SQL path, and bulk_create() inserts its list in
generally only one query; none of the three calls the model's
save(), and none sends either save signal. A model method that
every ordinary path calls therefore never sees these writes, so the
guarded field can move from one value to another with no check. A new
row is no safer: bulk_create() inserts it with no call to the
model's save(). Change the aggregate by loading it, sending its
root the action and saving it whole.
Default. Let a view or a form check a request's shape, and run the
use case in a plain function or class that opens
transaction.atomic(), loads, sends the command and saves, and
hands work for other systems to transaction.on_commit(), as
oo-placing-domain-logic rules 2 and 5,
oo-publishing-domain-events rule 3 and
oo-working-within-a-framework rule 2 ask. A view that loads a
model, checks its state and saves it keeps the use case at the edge:
a test needs a request to run it, and a second entry point cannot
reach it. A plain function or class takes the identifiers and
values, opens one atomic() block, loads the aggregate, sends it
the command, saves it and returns; atomic() works as a decorator
and as a context manager, and rolls the block back when an exception
leaves it. Work for another system waits for the commit:
transaction.on_commit() runs its callback after the transaction
commits, discards it on rollback, and runs it at once when no
transaction is open.
The exception is an entry point that changes one row through one
model method and hands nothing to another system, whether a view or a
plain function the view calls: it may call that method and save,
because autocommit mode commits the row's statement as it runs and
there is no second change to coordinate.
Rule. Put no business rule in a signal receiver: call the code
that reacts directly, as oo-working-within-a-framework rule 1
asks. A post_save receiver runs from save(): inside an
atomic() block it runs before that block commits, and it runs on
every save path, including one whose transaction later rolls back.
A receiver that writes another model or sends to another system
makes that effect happen wherever the save runs, and can send word
of a change that was never stored. It also hides the reaction from
the use case and from a test that calls the model method. The use
case calls the handling code itself, with no signal in between. It
calls the second model's change and the outside send itself: the
first inside its transaction, the second after the commit, as rule
3 says.
Judgement. Treat an app as a module with a public interface:
other apps call its functions rather than import its models, and an
app that is a context of its own refers to another app's rows by
identity rather than a ForeignKey, as
oo-organising-modules rule 6, oo-bounding-contexts rule 2 and
oo-designing-aggregates rule 3 ask. A Django application is a
Python package that provides some set of features, not a boundary by
itself: two apps whose models share one lifecycle may sit inside one
context, and an app is a context only while its own model, its own
words and its own rules stay inside it. Django makes the reach easy:
a model can take another app's class as a ForeignKey, either by
importing it or by naming it lazily as "app_label.ModelName", and
the migration writes a foreign key between the tables. Another app
then reads and writes rows its own rules do not govern. Publish the
functions other apps may call, keep the models inside, and store
another context's identity as a value with no foreign key, then load
what it names through the owning app's interface.
Default. Name a table-level query for the question the domain
asks, as a custom manager or QuerySet method, rather than a filter
repeated in views, as oo-designing-repositories rule 3 and
oo-layering-the-system rule 6 ask. A filter chain in a view
spells the question at the edge, so each caller writes its own
version and a change to the question touches every view. A manager
method is the usual home for a question about the whole table, and
QuerySet.as_manager() or Manager.from_queryset() gives the
manager and the queryset one set of query methods, so
RadiologyRequest.objects.due_today() answers the question from
either. A model method answers for one row, not a table, so a row's
rules stay on the model rather than on a manager.
The exception is a read of one row already named by its identity,
such as a detail screen loading the request whose primary key the
request carries: it needs no manager method, because the identity
already names the row and the read decides no rule.
Pattern
RadiologyRequest asks the clinic's radiology centre to take a scan for a
patient. Its status is guarded: only a requested scan may be
scheduled, and a request carries the moment it expires. The first
fence is a view that decides both rules and writes the status itself,
beside a second path that writes the same field with update(). The
fences after it move the check into the model's action method and call
it from both paths.
Before:
from django.http import HttpResponse
from django.utils import timezone
from .models import RadiologyRequest
def schedule_radiology_request(request, pk):
try:
radiology_request = RadiologyRequest.objects.get(pk=pk)
except RadiologyRequest.DoesNotExist:
return HttpResponse("no radiology request", status=404)
now = timezone.now()
if radiology_request.status != RadiologyRequest.REQUESTED:
return HttpResponse("already scheduled", status=409)
if now > radiology_request.expires_at:
return HttpResponse("expired", status=409)
radiology_request.status = RadiologyRequest.SCHEDULED
radiology_request.scheduled_at = now
radiology_request.save()
return HttpResponse("scheduled")
def schedule_from_waitlist(pk):
RadiologyRequest.objects.filter(pk=pk).update(
status=RadiologyRequest.SCHEDULED)
In the Before, RadiologyRequest is the model whose status a rule
guards, and its status and scheduled_at are public fields that any
caller can assign. schedule_radiology_request is the first path: it
reads the status and the expiry, decides both rules, and assigns the
two fields before it saves, so the rule lives in a view (rule 1). The
second path, schedule_from_waitlist, writes the guarded status with
update(), at the SQL level, so no check runs on that path at all
(rule 2). The first path stores a radiology request row under its
primary key in the radiology request table, with one save(); the
second path stores the same row with one SQL update. Neither path opens
a transaction of its own.
After, the model:
from datetime import datetime
from django.db import models
class RadiologyRequestExpired(Exception):
pass
class RadiologyRequestAlreadyScheduled(Exception):
pass
class RadiologyRequest(models.Model):
REQUESTED = "requested"
SCHEDULED = "scheduled"
STATUSES = [
(REQUESTED, "Requested"),
(SCHEDULED, "Scheduled"),
]
patient_number = models.CharField(max_length=200)
kind = models.CharField(max_length=100)
expires_at = models.DateTimeField()
_status = models.CharField(
max_length=20, choices=STATUSES, default=REQUESTED,
db_column="status")
_scheduled_at = models.DateTimeField(
null=True, blank=True, db_column="scheduled_at")
@property
def status(self) -> str:
return self._status
@property
def scheduled_at(self) -> datetime | None:
return self._scheduled_at
def schedule(self, now: datetime) -> None:
if self._status != RadiologyRequest.REQUESTED:
raise RadiologyRequestAlreadyScheduled(self.pk)
if now > self.expires_at:
raise RadiologyRequestExpired(self.pk)
self._status = RadiologyRequest.SCHEDULED
self._scheduled_at = now
After, both paths:
from collections.abc import Callable
from datetime import datetime
from django.http import HttpResponse
from .models import (
RadiologyRequest,
RadiologyRequestAlreadyScheduled,
RadiologyRequestExpired,
)
def schedule_radiology_request(
request, pk: int, clock: Callable[[], datetime]) -> HttpResponse:
try:
radiology_request = RadiologyRequest.objects.get(pk=pk)
except RadiologyRequest.DoesNotExist:
return HttpResponse("no radiology request", status=404)
now = clock()
try:
radiology_request.schedule(now)
except RadiologyRequestAlreadyScheduled:
return HttpResponse("already scheduled", status=409)
except RadiologyRequestExpired:
return HttpResponse("expired", status=409)
radiology_request.save()
return HttpResponse("scheduled")
def schedule_from_waitlist(
request, pk: int, clock: Callable[[], datetime]) -> HttpResponse:
try:
radiology_request = RadiologyRequest.objects.get(pk=pk)
except RadiologyRequest.DoesNotExist:
return HttpResponse("no radiology request", status=404)
now = clock()
try:
radiology_request.schedule(now)
except RadiologyRequestAlreadyScheduled:
return HttpResponse("already scheduled", status=409)
except RadiologyRequestExpired:
return HttpResponse("expired", status=409)
radiology_request.save()
return HttpResponse("scheduled")
The URLconf is the composition root for both views:
from django.urls import path
from django.utils import timezone
from . import views
urlpatterns = [
path(
"radiology/<int:pk>/schedule/",
views.schedule_radiology_request,
{"clock": timezone.now},
),
path(
"waitlist/<int:pk>/schedule/",
views.schedule_from_waitlist,
{"clock": timezone.now},
),
]
RadiologyRequest is an active record: its class mirrors the radiology
request table, and schedule is its one action method. The two fields
the rule guards are private, _status and _scheduled_at, each read
through a property with no setter and each keeping its table column
name through db_column; a caller's assignment raises AttributeError,
so only schedule changes them (oo-python rule 4). schedule checks
the status and the expiry and raises RadiologyRequestExpired or
RadiologyRequestAlreadyScheduled before it assigns either field, so a
refused call changes nothing (rule 1). Both paths call the same method:
neither view reads the status or the expiry, and
schedule_from_waitlist uses no update(), bulk_update() or
bulk_create() (rule 2). The URLconf fence stores nothing: it is the
composition root, giving each view the timezone.now callable as its
clock keyword. Each view asks that callable once and passes the answer
to schedule, so neither view reaches a static clock. The two paths
store a radiology request row under its primary key in the radiology
request table, each with one save(); neither opens a transaction of
its own, and each changes one row and hands nothing to another system,
which is the exception rule 3 states. Both entry paths call the model's
method; two requests that load the same radiology request at once both
pass it and both save. select_for_update() inside a transaction, left
out of this fence, makes the second wait on a store that provides row
locks and then load the scheduled row, which schedule refuses. The
state keeps rules 1 and 2 and oo-designing-for-testability rule 5:
the rule sits in schedule, neither path writes the guarded field with
update(), bulk_update() or bulk_create(), and each view receives
its clock from the composition root instead of reaching a static one.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A rule in
clean() or ModelForm.clean() that a save() path
depends on.
- A view that reads a status or a date, decides, and then assigns the
field it guards.
QuerySet.update(), bulk_update() or bulk_create() on a field a
rule guards.
- A
post_save receiver that writes another model, sends a message or
enqueues a job.
- A signal receiver that holds a rule rather than a notification.
- A view that saves several models with no
transaction.atomic().
- Work for another system sent before
transaction.on_commit().
- An app that imports another app's models, or a
ForeignKey between
two apps that keep separate models.
- A filter chain repeated in several views with no manager or
QuerySet method naming the question.
- A custom manager that hands out a query builder instead of answering
a named question.
Common mistakes
- Moving a rule from a view into
clean() and believing save() now
runs it.
- Trusting
full_clean() to run because a ModelForm validated the
same object earlier.
- Using
update() to skip a model method without noticing the rule
that method holds.
- Calling
bulk_update() for speed on a field a rule guards.
- Putting a second model's write in a
post_save receiver so every
save gets the effect, intended or not.
- Sending to another system inside the transaction and believing a
rollback takes the message back.
- Treating a Django app as a boundary because its directory has its own
name.
- Naming a query after a column instead of the question the clinic
asks.
- Adding a custom manager method for a read of one row by its primary
key.
- Keeping every rule on one large model because Django's ORM makes
saving convenient.
Related skills
oo-python holds the language rules this skill applies, including
its rules on protocols, frozen dataclasses and state kept behind its
class.
oo-working-within-a-framework decides what a framework may shape
and what stays in the domain.
oo-encapsulating-state-and-behaviour keeps state behind methods
named for domain actions.
oo-designing-failure-behaviour names a refusal and raises it before
a change.
oo-designing-for-testability passes a value such as the time into a
domain method.
oo-placing-domain-logic places a use case and its transaction.
oo-publishing-domain-events says when work waits for a commit.
oo-organising-modules gives a module a public interface.
oo-bounding-contexts decides where one model ends and another
begins.
oo-designing-aggregates decides what one transaction changes.
oo-designing-repositories declares a read in the domain's words.
oo-layering-the-system keeps a read that decides nothing out of the
domain.
oo-separating-presentation-from-domain splits a screen's state from
the domain.
Further reading
1---2name: oo-python-django3description: Use when a Django project's models, views or signals carry business rules, or its apps are being drawn as boundaries.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-python-django7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing Objects in Django1213**In this pack:** sizing and rule strictness are set by the core14plugin's `oo-design` skill; each rule here keeps a core rule in this15language.1617## Overview1819This skill holds only what Django changes on top of `oo-python`: load20that skill too, because its rules on protocols, frozen dataclasses and21state kept behind its class still hold in a Django code base. Django22supplies an object-relational mapper whose model classes stand for23rows and save themselves, forms and views at the edge, signal receivers24that run when a model is saved, and apps that may import each other's25models. Each of those offers a place to keep a decision that belongs to26the domain: a `clean()` method that `save()` never runs, a view that27sets a guarded field, a bulk update that writes behind every model28method, a signal receiver that holds a reaction, and apps that import29each other's models until no boundary is left. Django 6.1 on Python303.12 or later changes where these rules are kept, not what they31require.3233## When to use3435- A rule that guards a status change sits in `clean()`, a view or a36 form, and a `save()` path reaches the field without it.37- A view, a management command or a script changes a guarded field with38 `QuerySet.update()`, `bulk_update()` or `bulk_create()`.39- A `pre_save` or `post_save` receiver writes another model, sends to40 another system, or holds a rule.41- A view or a form decides whether a change is allowed, or one request42 opens several saves.43- Two apps import each other's models, or one app reads another app's44 table as its own.45- A filter chain is repeated in views instead of named on a manager or46 a `QuerySet`.4748## When not to use4950- The code is plain Python that imports nothing from Django, which51 `oo-python` covers.52- The question is how a template or a front-end component splits its53 state from the domain: outside this skill, and54 `oo-separating-presentation-from-domain` covers the core rule.55- A question no Django feature changes, such as which object owns a56 rule: the core skills, starting from `oo-design`.5758## Core rules59601. Rule. **Keep a rule that guards a state change in a model method61 named for the action, which takes the time it needs as a parameter62 and checks before it changes anything, because `save()` never runs63 `full_clean()`, so a rule that lives only in `clean()` holds only64 for forms, as `oo-working-within-a-framework` rule 1,65 `oo-encapsulating-state-and-behaviour` rules 1 and 3,66 `oo-designing-failure-behaviour` rule 4 and67 `oo-designing-for-testability` rule 3 ask.** `save()` runs neither68 `full_clean()` nor `clean()`, the hook for validation that needs more69 than one field; a `ModelForm` runs the model's validation for the70 fields the form holds, so a rule in `clean()` refuses a form's71 invalid input and lets a script, a view that assigns a field, or a72 bulk write past it. A model method such as `schedule(now)` reads the73 current state, refuses the call in the clinic's words before it74 assigns anything, and writes only when the rule holds; the time it75 decides with arrives as a parameter, so a test passes the time it76 chooses.77782. Rule. **Never change state that a rule guards with79 `QuerySet.update()`, `bulk_update()` or `bulk_create()`, which call80 no `save()` and send no `pre_save` or `post_save`, as81 `oo-designing-repositories` rule 6 asks.** `update()` runs an SQL82 update for the rows it matches, `bulk_update()` saves its changes83 through the same SQL path, and `bulk_create()` inserts its list in84 generally only one query; none of the three calls the model's85 `save()`, and none sends either save signal. A model method that86 every ordinary path calls therefore never sees these writes, so the87 guarded field can move from one value to another with no check. A new88 row is no safer: `bulk_create()` inserts it with no call to the89 model's `save()`. Change the aggregate by loading it, sending its90 root the action and saving it whole.91923. Default. **Let a view or a form check a request's shape, and run the93 use case in a plain function or class that opens94 `transaction.atomic()`, loads, sends the command and saves, and95 hands work for other systems to `transaction.on_commit()`, as96 `oo-placing-domain-logic` rules 2 and 5,97 `oo-publishing-domain-events` rule 3 and98 `oo-working-within-a-framework` rule 2 ask.** A view that loads a99 model, checks its state and saves it keeps the use case at the edge:100 a test needs a request to run it, and a second entry point cannot101 reach it. A plain function or class takes the identifiers and102 values, opens one `atomic()` block, loads the aggregate, sends it103 the command, saves it and returns; `atomic()` works as a decorator104 and as a context manager, and rolls the block back when an exception105 leaves it. Work for another system waits for the commit:106 `transaction.on_commit()` runs its callback after the transaction107 commits, discards it on rollback, and runs it at once when no108 transaction is open.109110 The exception is an entry point that changes one row through one111 model method and hands nothing to another system, whether a view or a112 plain function the view calls: it may call that method and save,113 because autocommit mode commits the row's statement as it runs and114 there is no second change to coordinate.1151164. Rule. **Put no business rule in a signal receiver: call the code117 that reacts directly, as `oo-working-within-a-framework` rule 1118 asks.** A `post_save` receiver runs from `save()`: inside an119 `atomic()` block it runs before that block commits, and it runs on120 every save path, including one whose transaction later rolls back.121 A receiver that writes another model or sends to another system122 makes that effect happen wherever the save runs, and can send word123 of a change that was never stored. It also hides the reaction from124 the use case and from a test that calls the model method. The use125 case calls the handling code itself, with no signal in between. It126 calls the second model's change and the outside send itself: the127 first inside its transaction, the second after the commit, as rule128 3 says.1291305. Judgement. **Treat an app as a module with a public interface:131 other apps call its functions rather than import its models, and an132 app that is a context of its own refers to another app's rows by133 identity rather than a `ForeignKey`, as134 `oo-organising-modules` rule 6, `oo-bounding-contexts` rule 2 and135 `oo-designing-aggregates` rule 3 ask.** A Django application is a136 Python package that provides some set of features, not a boundary by137 itself: two apps whose models share one lifecycle may sit inside one138 context, and an app is a context only while its own model, its own139 words and its own rules stay inside it. Django makes the reach easy:140 a model can take another app's class as a `ForeignKey`, either by141 importing it or by naming it lazily as `"app_label.ModelName"`, and142 the migration writes a foreign key between the tables. Another app143 then reads and writes rows its own rules do not govern. Publish the144 functions other apps may call, keep the models inside, and store145 another context's identity as a value with no foreign key, then load146 what it names through the owning app's interface.1471486. Default. **Name a table-level query for the question the domain149 asks, as a custom manager or `QuerySet` method, rather than a filter150 repeated in views, as `oo-designing-repositories` rule 3 and151 `oo-layering-the-system` rule 6 ask.** A filter chain in a view152 spells the question at the edge, so each caller writes its own153 version and a change to the question touches every view. A manager154 method is the usual home for a question about the whole table, and155 `QuerySet.as_manager()` or `Manager.from_queryset()` gives the156 manager and the queryset one set of query methods, so157 `RadiologyRequest.objects.due_today()` answers the question from158 either. A model method answers for one row, not a table, so a row's159 rules stay on the model rather than on a manager.160161 The exception is a read of one row already named by its identity,162 such as a detail screen loading the request whose primary key the163 request carries: it needs no manager method, because the identity164 already names the row and the read decides no rule.165166## Pattern167168`RadiologyRequest` asks the clinic's radiology centre to take a scan for a169patient. Its status is guarded: only a requested scan may be170scheduled, and a request carries the moment it expires. The first171fence is a view that decides both rules and writes the status itself,172beside a second path that writes the same field with `update()`. The173fences after it move the check into the model's action method and call174it from both paths.175176Before:177178```python179from django.http import HttpResponse180from django.utils import timezone181182from .models import RadiologyRequest183184185def schedule_radiology_request(request, pk):186 try:187 radiology_request = RadiologyRequest.objects.get(pk=pk)188 except RadiologyRequest.DoesNotExist:189 return HttpResponse("no radiology request", status=404)190 now = timezone.now()191 if radiology_request.status != RadiologyRequest.REQUESTED:192 return HttpResponse("already scheduled", status=409)193 if now > radiology_request.expires_at:194 return HttpResponse("expired", status=409)195 radiology_request.status = RadiologyRequest.SCHEDULED196 radiology_request.scheduled_at = now197 radiology_request.save()198 return HttpResponse("scheduled")199200201def schedule_from_waitlist(pk):202 RadiologyRequest.objects.filter(pk=pk).update(203 status=RadiologyRequest.SCHEDULED)204```205206In the Before, `RadiologyRequest` is the model whose `status` a rule207guards, and its `status` and `scheduled_at` are public fields that any208caller can assign. `schedule_radiology_request` is the first path: it209reads the status and the expiry, decides both rules, and assigns the210two fields before it saves, so the rule lives in a view (rule 1). The211second path, `schedule_from_waitlist`, writes the guarded status with212`update()`, at the SQL level, so no check runs on that path at all213(rule 2). The first path stores a radiology request row under its214primary key in the radiology request table, with one `save()`; the215second path stores the same row with one SQL update. Neither path opens216a transaction of its own.217218After, the model:219220```python221from datetime import datetime222223from django.db import models224225226class RadiologyRequestExpired(Exception):227 pass228229230class RadiologyRequestAlreadyScheduled(Exception):231 pass232233234class RadiologyRequest(models.Model):235 REQUESTED = "requested"236 SCHEDULED = "scheduled"237 STATUSES = [238 (REQUESTED, "Requested"),239 (SCHEDULED, "Scheduled"),240 ]241242 patient_number = models.CharField(max_length=200)243 kind = models.CharField(max_length=100)244 expires_at = models.DateTimeField()245 _status = models.CharField(246 max_length=20, choices=STATUSES, default=REQUESTED,247 db_column="status")248 _scheduled_at = models.DateTimeField(249 null=True, blank=True, db_column="scheduled_at")250251 @property252 def status(self) -> str:253 return self._status254255 @property256 def scheduled_at(self) -> datetime | None:257 return self._scheduled_at258259 def schedule(self, now: datetime) -> None:260 if self._status != RadiologyRequest.REQUESTED:261 raise RadiologyRequestAlreadyScheduled(self.pk)262 if now > self.expires_at:263 raise RadiologyRequestExpired(self.pk)264 self._status = RadiologyRequest.SCHEDULED265 self._scheduled_at = now266```267268After, both paths:269270```python271from collections.abc import Callable272from datetime import datetime273274from django.http import HttpResponse275276from .models import (277 RadiologyRequest,278 RadiologyRequestAlreadyScheduled,279 RadiologyRequestExpired,280)281282283def schedule_radiology_request(284 request, pk: int, clock: Callable[[], datetime]) -> HttpResponse:285 try:286 radiology_request = RadiologyRequest.objects.get(pk=pk)287 except RadiologyRequest.DoesNotExist:288 return HttpResponse("no radiology request", status=404)289 now = clock()290 try:291 radiology_request.schedule(now)292 except RadiologyRequestAlreadyScheduled:293 return HttpResponse("already scheduled", status=409)294 except RadiologyRequestExpired:295 return HttpResponse("expired", status=409)296 radiology_request.save()297 return HttpResponse("scheduled")298299300def schedule_from_waitlist(301 request, pk: int, clock: Callable[[], datetime]) -> HttpResponse:302 try:303 radiology_request = RadiologyRequest.objects.get(pk=pk)304 except RadiologyRequest.DoesNotExist:305 return HttpResponse("no radiology request", status=404)306 now = clock()307 try:308 radiology_request.schedule(now)309 except RadiologyRequestAlreadyScheduled:310 return HttpResponse("already scheduled", status=409)311 except RadiologyRequestExpired:312 return HttpResponse("expired", status=409)313 radiology_request.save()314 return HttpResponse("scheduled")315```316317The URLconf is the composition root for both views:318319```python320from django.urls import path321from django.utils import timezone322323from . import views324325urlpatterns = [326 path(327 "radiology/<int:pk>/schedule/",328 views.schedule_radiology_request,329 {"clock": timezone.now},330 ),331 path(332 "waitlist/<int:pk>/schedule/",333 views.schedule_from_waitlist,334 {"clock": timezone.now},335 ),336]337```338339`RadiologyRequest` is an active record: its class mirrors the radiology340request table, and `schedule` is its one action method. The two fields341the rule guards are private, `_status` and `_scheduled_at`, each read342through a property with no setter and each keeping its table column343name through `db_column`; a caller's assignment raises `AttributeError`,344so only `schedule` changes them (`oo-python` rule 4). `schedule` checks345the status and the expiry and raises `RadiologyRequestExpired` or346`RadiologyRequestAlreadyScheduled` before it assigns either field, so a347refused call changes nothing (rule 1). Both paths call the same method:348neither view reads the status or the expiry, and349`schedule_from_waitlist` uses no `update()`, `bulk_update()` or350`bulk_create()` (rule 2). The URLconf fence stores nothing: it is the351composition root, giving each view the `timezone.now` callable as its352`clock` keyword. Each view asks that callable once and passes the answer353to `schedule`, so neither view reaches a static clock. The two paths354store a radiology request row under its primary key in the radiology355request table, each with one `save()`; neither opens a transaction of356its own, and each changes one row and hands nothing to another system,357which is the exception rule 3 states. Both entry paths call the model's358method; two requests that load the same radiology request at once both359pass it and both save. `select_for_update()` inside a transaction, left360out of this fence, makes the second wait on a store that provides row361locks and then load the scheduled row, which `schedule` refuses. The362state keeps rules 1 and 2 and `oo-designing-for-testability` rule 5:363the rule sits in `schedule`, neither path writes the guarded field with364`update()`, `bulk_update()` or `bulk_create()`, and each view receives365its clock from the composition root instead of reaching a static one.366367## Red flags368369Places to look, not verdicts. A red flag becomes a finding only with370evidence: a measurement, a reproducible bug, or a failing test.371372- A rule in `clean()` or `ModelForm.clean()` that a `save()` path373 depends on.374- A view that reads a status or a date, decides, and then assigns the375 field it guards.376- `QuerySet.update()`, `bulk_update()` or `bulk_create()` on a field a377 rule guards.378- A `post_save` receiver that writes another model, sends a message or379 enqueues a job.380- A signal receiver that holds a rule rather than a notification.381- A view that saves several models with no `transaction.atomic()`.382- Work for another system sent before `transaction.on_commit()`.383- An app that imports another app's models, or a `ForeignKey` between384 two apps that keep separate models.385- A filter chain repeated in several views with no manager or386 `QuerySet` method naming the question.387- A custom manager that hands out a query builder instead of answering388 a named question.389390## Common mistakes391392- Moving a rule from a view into `clean()` and believing `save()` now393 runs it.394- Trusting `full_clean()` to run because a `ModelForm` validated the395 same object earlier.396- Using `update()` to skip a model method without noticing the rule397 that method holds.398- Calling `bulk_update()` for speed on a field a rule guards.399- Putting a second model's write in a `post_save` receiver so every400 save gets the effect, intended or not.401- Sending to another system inside the transaction and believing a402 rollback takes the message back.403- Treating a Django app as a boundary because its directory has its own404 name.405- Naming a query after a column instead of the question the clinic406 asks.407- Adding a custom manager method for a read of one row by its primary408 key.409- Keeping every rule on one large model because Django's ORM makes410 saving convenient.411412## Related skills413414- `oo-python` holds the language rules this skill applies, including415 its rules on protocols, frozen dataclasses and state kept behind its416 class.417- `oo-working-within-a-framework` decides what a framework may shape418 and what stays in the domain.419- `oo-encapsulating-state-and-behaviour` keeps state behind methods420 named for domain actions.421- `oo-designing-failure-behaviour` names a refusal and raises it before422 a change.423- `oo-designing-for-testability` passes a value such as the time into a424 domain method.425- `oo-placing-domain-logic` places a use case and its transaction.426- `oo-publishing-domain-events` says when work waits for a commit.427- `oo-organising-modules` gives a module a public interface.428- `oo-bounding-contexts` decides where one model ends and another429 begins.430- `oo-designing-aggregates` decides what one transaction changes.431- `oo-designing-repositories` declares a read in the domain's words.432- `oo-layering-the-system` keeps a read that decides nothing out of the433 domain.434- `oo-separating-presentation-from-domain` splits a screen's state from435 the domain.436437## Further reading438439- [Signals to direct calls](references/signals-to-direct-calls.md)