Concurrency fix 3: optimistic locking with a version field

Django Concurrency November 13, 2026 python

How do you implement optimistic locking with a version field in Django?

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ======================================================================
# Q: How do you implement optimistic locking with a version field in Django?
# ======================================================================

class Document(models.Model):
    body = models.TextField()
    version = models.PositiveIntegerField(default=0)

def save_document(doc_id, new_body, expected_version):
    rows = (Document.objects
            .filter(pk=doc_id, version=expected_version)
            .update(body=new_body, version=F('version') + 1))
    if rows == 0:
        raise ConflictError('Someone else changed the document')  # HTTP 409 -> reload/merge