问题
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.
回答1:
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:
from django.db import transaction
@transaction.commit_manually
def viewfunc(request):
...
# You can commit/rollback however and whenever you want
transaction.commit()
...
# But you've got to remember to do it yourself!
try:
...
except:
transaction.rollback()
else:
transaction.commit()
来源:https://stackoverflow.com/questions/6932006/django-deferring-save-of-graph-of-model-objects-transactionally-create-model