Django 推迟模型对象图的 save() / 以事务方式创建模型
我正在创建一堆相互引用的模型对象,如下所示:
link = DirectorsIndividual(company = co,
individual = individual,
director = officer)
其中 co
、individual
和 officer
是未保存的模型对象。因为它们尚未保存,所以还没有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 commit_manually 装饰器,如果您需要完全控制交易。它告诉 Django 你将自己管理事务。
如果你的视图更改了数据并且没有 commit() 或 rollback(),Django 将引发 TransactionManagementError 异常。
手动事务管理如下所示:
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: