首页 > 解决方案 > 如何在 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()

我们如何以不会导致竞争条件问题的线程安全方式做到这一点?

标签: pythonsqldjangopostgresqlrace-condition

解决方案


推荐阅读