开发者

Django deferring save() of graph of model objects / transactionally create models

I'm creating a bunch of model objects that refer to each other, like so:

开发者_如何学Golink = 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:

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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜