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

查看:488
本文介绍了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 )会导致单个数据库查询,因为过滤器是惰性的

  • 数据库查询是原子的

这些假设足以确保没有人以前更新过该条目。如果多个列都更新,您应该使用交易。

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