Shipmind Labs

Auditing Django model changes without a read before every write

· 9 min read

A field-level audit trail has to name the old value of every field it reports, and the obvious way to get that value is to read the row back right before each save. That doubles the queries on exactly the path the trail was installed to observe, on every write, forever. The alternative is to keep the values the instance was already holding when Django loaded it and diff against those: no extra query, at the price of a baseline that means something slightly narrower than "what the database holds now".

That trade is the whole design of model-audit, a Django library we maintain for field-level diffs on save. It records, it never stores. You declare which models are audited, you subscribe a receiver, and you send records wherever the project already keeps its logs. The part that has to be right is where the old side of a diff comes from, because everything else follows from it.

The constraint: the write path is the hot path#

Audit requirements land on the paths that matter. An invoice total, a payout state, a KYC decision, the writes worth recording are the writes under load, inside transactions, often inside a loop. A recorder that issues a SELECT before every UPDATE adds a query, a round trip and a lock window to each of them, and it adds them in proportion to how interesting the model is. We have inherited systems where that pattern turned a nightly reconciliation job into something that looked like a database capacity problem.

So the rule we hold to: the recorder never queries the database to learn what a row used to hold. Everything below is a consequence.

The snapshot is taken where the row arrives#

register() connects three signals for one model, post_init, post_save and post_delete, under a dispatch uid derived from the model, so registering the same model twice replaces the configuration and the handlers do not stack. Models that were never registered stay untouched: no signal receivers, and no library attributes on their instances.

The post_init handler does one thing.

python
def _on_post_init(sender: type[Model], instance: Model, **kwargs: Any) -> None:
    registration = _registrations.get(sender)
    if registration is None:
        return
    setattr(instance, _STATE_ATTR, _snapshot(instance, registration))

And the snapshot itself reads attributes, nothing more.

python
def _snapshot(instance: Model, registration: _Registration) -> dict[str, Any]:
    deferred = instance.get_deferred_fields()
    values: dict[str, Any] = {}
    for field in instance._meta.concrete_fields:
        # attname keeps a relation as its stored id, so reading it never
        # triggers a query for the related object.
        if field.attname in deferred or not _audited(field, registration):
            continue
        value = getattr(instance, field.attname)
        values[field.attname] = EXPRESSION if _is_expression(value) else value
    return values

Three details in that loop carry most of the weight.

It walks concrete_fields and reads field.attname. That is the stored attribute, so for a foreign key you get customer_id, a plain integer sitting on the instance. Reading instance.customer would fetch the related row, one query per relation per snapshot, triggered by a library whose entire premise is that it adds none.

It skips anything in get_deferred_fields(). A row loaded with .only("total") has no value for the other columns in memory, and touching them would trigger a per-field refresh. A deferred field is therefore skipped, not fetched: a narrower load gives you a narrower trail, which is the honest outcome here.

And it replaces anything that carries resolve_expression with a marker. After article.views = F("views") + 1 the attribute holds a CombinedExpression until the row is reloaded. Since the recorder never queries, it cannot know the resulting number, and handing a receiver that object would produce something json.dumps refuses. Inside a signal, that failure kills the save. EXPRESSION is a str subclass that serializes as "[expression]", while value is EXPRESSION still separates it from a stored string that happens to read the same way. The record says "changed by an expression" and declines to guess.

One more thing about post_init: it fires from inside Model.__init__, and from_db clears _state.adding only afterwards, so the flag cannot distinguish a loaded row from a brand-new one at that point. We do not try. New instances get snapshotted too, which is harmless, because a creation is diffed against an empty baseline regardless.

The diff on save#

python
incoming = _snapshot(instance, registration)
# An instance built before its model was registered carries no snapshot;
# its fields are then reported as additions rather than guessed at.
stored: dict[str, Any] = {} if created else getattr(instance, _STATE_ATTR, {})
setattr(instance, _STATE_ATTR, incoming)

fields = None
if update_fields is not None and not created:
    touched = _touched_attnames(sender, update_fields)
    fields = [name for name in incoming if name in touched]

changes = diff(stored, incoming, fields=fields)
if not changes and not created:
    return

The write-back on line 4 matters more than it looks: the new snapshot becomes the baseline before the diff is computed, so a second save on the same instance compares against the first save rather than against the original load. An object mutated and saved three times in a request produces three records that chain, each one measured against the snapshot the previous save left behind.

update_fields is honoured. _touched_attnames maps each declared name through _meta.get_field to its attname, so update_fields=["customer"] narrows to customer_id, and on FieldDoesNotExist it keeps the raw name and does not raise, because a save that Django accepts should not be turned into an error by an audit layer. The diff is then restricted to the fields the save actually wrote:

python
def test_update_fields_narrows_the_diff(records):
    register(Customer)
    customer = Customer.objects.create(name="Ada", email="ada@example.com")
    records.clear()

    customer.name = "Ada Lovelace"
    customer.email = "ada@lovelace.example"
    customer.save(update_fields=["email"])

    (record,) = records
    assert record.changes.as_dict() == {
        "email": ("ada@example.com", "ada@lovelace.example")
    }

The in-memory name change is real, but the database never saw it. Recording it would turn the trail into a description of the process. The row is what the trail reports on.

The last two lines are the other half of the thesis. An update whose changeset is empty emits nothing. A save() that rewrote the same values, a form submitted twice, an idempotent retry, the trail stays silent, so its volume tracks actual change rather than write traffic. A creation always emits, even when every field matches the model defaults, because the row coming into existence is the event. Deletions use the same snapshot function at post_delete, where the collector has not yet cleared the primary key, so the record can name both the row and the values it held, again without a query.

An instance that was constructed before its model was registered carries no baseline at all. We do not invent one. The empty dict flows into diff, which reports a field present on only one side as MISSING on the other, and FieldChange exposes that as is_addition. The record reads "these fields now hold these values", which is exactly what we know.

What the baseline does and does not mean#

The honest statement of the trade: the old value is what this process loaded, not what the row contained an instant before the write. If another worker updated the row in between, our diff shows the change relative to a stale baseline. For an audit trail answering "who changed what, and to what" that is probably the right answer anyway, since it describes the actor's intent on the data they were shown, but it is not a substitute for optimistic locking, and we say so when a project's requirement is really concurrency control rather than attribution.

The same reasoning sets the other limits. Queryset-level writes do not send post_save, so set-based updates leave no model record. When a flow needs to be in the trail, it has to go through instance saves, or be recorded at the request layer. And since snapshots hold raw field values in memory, redaction has to happen on the way out: the record's changeset passes through the registration's redactor, which withholds values whose field name matches a sensitive pattern while keeping MISSING intact so an addition still reads as one.

What it costs to run#

One dict of field values per audited instance, alive as long as the instance is. post_init fires for every row a queryset materializes, so iterating ten thousand audited rows takes ten thousand snapshots. Cheap attribute reads, but not free, and that is why register(..., fields=[...]), exclude=[...] and a deliberate .only() on bulk read paths all pay off, since a narrower registration and a narrower load both shrink the snapshot.

Receivers run inline inside the signal, which means a receiver that talks over the network puts its latency on the save and its failures inside the transaction. Ours hand the record to a logger or a queue and return.

Close#

The design is one sentence long, never query for the old values, and the awkward cases are not special-cased, they are restatements of it. A deferred field is skipped because fetching it would be a query. An expression becomes a marker because resolving it would be a query. A missing baseline becomes a set of additions because reconstructing it would be a query. The trail describes what this process did to this instance, and it adds nothing to the write path to do it.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com