liveBook · Manning

Database transaction

As explained in Django in Action

A database transaction is an atomic group of database actions that either completes as a unit or can be rolled back as a unit.

A database transaction groups several database actions into one atomic unit: either the whole group completes, or the changes can be rolled back. Django uses this idea to keep tests isolated. Each test method runs inside a transaction, and Django rolls back its database changes when the method finishes. section 8.3

A Django database test typically follows this flow:

  • Start with Django’s separate test database, which begins empty. section 8.3
  • Create required ORM objects in setUp(), such as a Musician used by every test. section 8.3
  • Call the view through Django’s test client and inspect its response. section 8.10
  • Finish the test and let Django roll back its transaction, leaving the test database ready for the next test. section 8.3

Testing a musician view

setUp() creates a Musician object. test_musician_view() requests /bands/musician/<id>/, then checks for a 200 status, the expected object in the response context, and the musician’s name in the rendered content. Afterward, the transaction undoes the created database state. section 8.3

How Django in Action covers it

How deep it goes
Explains atomic grouping and automatic rollback within Django tests, without detailing broader application-level transaction management.
Examples
Uses a Musician fixture and a client request to test status, response context, and rendered content.
What it assumes
Assumes basic Django tests and ORM models while establishing the test database and transaction behavior through examples.
What you can do after
Diagnose test isolation by creating ORM fixtures, exercising views, checking responses, and relying on rollback between methods.
How it connects
Connects database transactions with Django TestCase, ORM objects, setUp(), test databases, and the test client.

Also explained in

Compare how 14 books explain database transaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.