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

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

问题描述

Django中的create()方法创建一个模型实例,然后调用save(),这被称为触发提交。所以触发事务的提交不应该有什么区别。



但实际上,执行一个在Postgresql上使用create()创建一堆模型实例的方法我得到事务中止,命令被忽略直到交易结束异常。该方法运行正常与非事务db后端。此外,当我用以下代码替换create()s时:

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

它在Postgresql上运行也很好。 >

使用 save() create()在交易意义上



编辑: create()还设置 self._for_write = True 调用save()之前,但我无法追踪它,看看它是否对事务行为有任何影响。



编辑: strong>示例代码可以在这里找到。

解决方案

如你所见, create()只是 save() 的包装器:



_for_write 部分最有可能仅用于数据库选择,所以我不会太重视它。



关于事务中止错误,没有看到你的代码,很难说出什么问题。也许你违反了UNIQUE约束与create(),这导致PostgreSQL要求事务回滚,然后您尝试 save()与不同的数据 - 很难说没有确切的代码。 / p>

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.

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

it runs on Postgresql fine too.

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

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.

edit: example code can be found here.

解决方案

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

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

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天全站免登陆