python - 如何在 Django 中根据属于数据库中最后一个类似对象的值为整数字段分配值时避免竞争条件?
问题描述
一些显示问题的示例代码:
class Post(models.Model):
...
class Comment(models.Model):
...
post = models.ForeignKey(Post, related_name='comments',
on_delete=models.CASCADE, null=False)
post_comment_number = models.PositiveIntegerField(unique=True, null=False)
假设每次我们为 Post 对象创建一个新的 Comment 对象时,我们希望为 post_comment_number 字段分配一个值,该值是为同一 Post 对象创建的最后一条评论的 post_comment_number 值的 +1。
我相信执行以下操作可能会导致竞争条件问题:
last_comment_for_post = Comment.objects.filter(post=post).order_by('-post_comment_number')[0]
comment = comment_form.save(commit=False)
comment.post_comment_number = last_comment_for_post.post_comment_number + 1
comment.save()
我们如何以不会导致竞争条件问题的线程安全方式做到这一点?
解决方案
推荐阅读
- python - 在numpy数组的特定行中,如何查找前3个最大值的列索引
- php - 运行 php 的 msg_get_queue() 时,有没有办法指定队列的组所有权?
- javascript - 如何在另一个 div 中剪切超出的 div 内容?
- python - 如何将 Python 使用者连接到 AWS MSK
- node.js - node.js firestore 缓存快照并在重新启动后仍然存在
- mapbox - Mapbox 未在 netlify 上加载地图
- excel - Powershell Excel 像双击一样激活单元格并发送 Enter
- c# - 使用 Any() 关键字对反射属性的值进行空检查
- snowflake-cloud-data-platform - 我正在运行一个大的 sql 查询并且有一个编译内存耗尽错误,增加仓库大小就足够了吗?
- c# - ClientWebSocket.ConnectAsync 立即关闭