I’m creating a bunch of model objects that refer to each other, like so:
link = DirectorsIndividual(company = co,
individual = individual,
director = officer)
Where co, individual, and officer are unsaved model objects. Because they’re unsaved, they don’t yet have ids, so saving link will cause an error.
I want to either create and save all of my objects, or none of them. Is there a standard pattern for doing this?
I’m doing this because I care about “transactionality”; minimising database access is obviously also good, but not the primary objective.
Use the commit_manually decorator if you need full control over transactions. It tells Django you’ll be managing the transaction on your own.
If your view changes data and doesn’t commit() or rollback(), Django will raise a TransactionManagementError exception.
Manual transaction management looks like this: