Django:从事务角度看 save() 和 create() 的区别 [英] Django: Difference between save() and create() from transaction perspective

查看:10
本文介绍了Django:从事务角度看 save() 和 create() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 中的 create() 方法会创建一个模型实例,然后调用 save(),据说会触发提交.所以触发事务的提交应该没有任何区别.

The create() method in Django creates a model instance then calls save(), which is said to trigger commit. So there should not be any difference in triggering transaction's commit.

但实际上,在 Postgresql 上使用 create() 执行一个创建一堆模型实例的方法时,我得到 transaction aborted, commands waiting until end of transaction 异常.该方法在非事务性数据库后端运行良好.另外,当我将 create()s 替换为:

But in reality, executing a method that creates a bunch of model instances using create() on Postgresql I am getting transaction aborted, commands ignored until end of transaction exception. The method runs fine with non-transactional db backends. Also, when I replace the create()s with:

m = Model(attr1=..., attr2=...)
m.save()

它也可以在 Postgresql 上正常运行.

it runs on Postgresql fine too.

使用save()create()在交易意义上有区别吗?

Is there a difference between using save() and create() in the sense of transactions?

edit: create() 在调用 save() 之前还设置了 self._for_write = True,但我无法追踪它以查看它是否对交易行为.

edit: create() also sets self._for_write = True before calling save(), but I couldn't trace it to see if it has any effect on transaction behavior.

示例代码可以在这里找到.

推荐答案

你可能已经看到,create() 只是对 save() 的封装:

As you've probably seen, create() is just a wrapper for save():

_for_write 部分 很可能只用于数据库选择,所以我不会过多关注它.

The _for_write part is most probably meant only for database selection, so I wouldn't pay too much attention to it.

关于事务中止"错误,如果没有看到您的代码,很难说出问题是什么.也许你例如使用 create() 违反了 UNIQUE 约束,这导致 PostgreSQL 要求事务回滚,然后您尝试 save() 使用不同的数据 - 如果没有确切的代码,很难判断.

And regarding that "transaction aborted" error, without seeing your code it's hard to say what the problem is. Maybe you e.g. violated UNIQUE constraint with create(), which causes PostgreSQL to demand transaction rollback, and then you tried save() with different data - it's hard to tell without the exact code.

这篇关于Django:从事务角度看 save() 和 create() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆