Django:如何防止数据库条目的并发修改 [英] Django: How can I protect against concurrent modification of database entries

查看:132
本文介绍了Django:如何防止数据库条目的并发修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一种方法可以防止两个或更多用户同时进行相同的数据库条目的修改?

If there a way to protect against concurrent modifications of the same data base entry by two or more users?

可以将错误信息显示给用户执行第二个提交/保存操作,但数据不应该被默认覆盖。

It would be acceptable to show an error message to the user performing the second commit/save operation, but data should not be silently overwritten.

我认为锁定条目不是一个选项,因为用户可能会使用返回或者简单地关闭他的浏览器,永远留下锁。

I think locking the entry is not an option, as a user might use the "Back" button or simply close his browser, leaving the lock for ever.

推荐答案

这是我如何在Django中做乐观锁定: / p>

This is how I do optimistic locking in Django:

updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\
          .update(updated_field=new_value, version=e.version+1)
if not updated:
    raise ConcurrentModificationException()

上面列出的代码可以作为自定义管理器

The code listed above can be implemented as a method in Custom Manager.

我做了以下假设:


  • filter()。update )将导致单个数据库查询,因为过滤器是懒惰

  • 数据库查询是原子

这些假设足以确保没有其他人更新该条目。如果以这种方式更新了多行,您应该使用交易。

These assumptions are enough to ensure that no one else has updated the entry before. If multiple rows are updated this way you should use transactions.

警告 Django Doc


请注意,update()方法是
直接转换为SQL
语句。这是
直接更新的批量操作。它不会在您的模型上运行任何
save()方法,或者发出
pre_save或post_save信号

Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn't run any save() methods on your models, or emit the pre_save or post_save signals

这篇关于Django:如何防止数据库条目的并发修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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