Django 推迟模型对象图的 save() / 以事务方式创建模型

发布于 2024-11-27 15:50:19 字数 424 浏览 2 评论 0原文

我正在创建一堆相互引用的模型对象,如下所示:

link = DirectorsIndividual(company = co,
                           individual = individual,
                           director = officer)

其中 coindividualofficer 是未保存的模型对象。因为它们尚未保存,所以还没有 id,因此保存 link 将导致错误。

我想要创建并保存所有对象,或者不创建并保存任何对象。是否有执行此操作的标准模式?

我这样做是因为我关心“交易性”;最小化数据库访问显然也是好的,但不是主要目标。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女净妖师 2024-12-04 15:50:19

使用 commit_manually 装饰器,如果您需要完全控制交易。它告诉 Django 你将自己管理事务。

如果你的视图更改了数据并且没有 commit() 或 rollback(),Django 将引发 TransactionManagementError 异常。

手动事务管理如下所示:

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文