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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 07:10:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!