此代码应该获取或创建一个对象,并在必要时更新它.该代码在网站上正在生产中使用.
在某些情况下 - 当数据库繁忙时 - 它将抛出异常"DoesNotExist:MyObj匹配查询不存在".
# Model:
class MyObj(models.Model):
thing = models.ForeignKey(Thing)
owner = models.ForeignKey(User)
state = models.BooleanField()
class Meta:
unique_together = (('thing', 'owner'),)
# Update or create myobj
@transaction.commit_on_success
def create_or_update_myobj(owner, thing, state)
try:
myobj, created = MyObj.objects.get_or_create(owner=user,thing=thing)
except IntegrityError:
myobj = MyObj.objects.get(owner=user,thing=thing)
# Will sometimes throw "DoesNotExist: MyObj matching query does not exist"
myobj.state = state
myobj.save()
Run Code Online (Sandbox Code Playgroud)
我在ubuntu上使用innodb mysql数据库.
我该如何安全地处理这个问题?
我想知道将Django与PostgreSQL数据库一起使用时的默认隔离级别是什么.可序列化隔离?(https://www.postgresql.org/docs/9.1/static/transaction-iso.html#XACT-SERIALIZABLE)
有一个关于MySQL的讨论(mysql和postgresql中的Django事务隔离级别),但尽管它的名字似乎没有讨论PostgreSQL
谢谢!