我正在使用Django1.8和mysql数据库。数据库隔离级别是“可重复读取的”。 我的代码如下:
@with transaction.atomic():
SomeModel.objects.create(key='aaa') # insert record
insertedRecord = SomeModel.objects.get(key='aaa') # try to fetch inserted record
我遇到的问题是,SomeModel.objects.get(key='aaa')
行会抛出DoesNotExist
异常,这意味着此查询无法查看先前创建操作所做的更改。
我在这里错过了什么吗?
答案 0 :(得分:1)
@with transaction.atomic():
SomeModel.objects.create(key='aaa') # insert record, used the master connection
insertedRecord = SomeModel.objects.get(key='aaa') # fetch record, used the slave connection
上面的代码基本上等于打开两个连接,一个写记录,一个读取记录。因此,除非写入事务首先完成,否则读取不会被触发。
相反,此代码将通过强制使用master读取记录来提供预期结果:
@with transaction.atomic():
SomeModel.objects.create(key='aaa') # insert record, used the master connection
insertedRecord = SomeModel.objects.using('master').get(key='aaa') # fetch record, force using master connection. Say `master` is alias for master connection