Some example code showing the issue:
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)
Say every time we create a new Comment object for a Post object, we want to assign the post_comment_number field a value that's +1 of the post_comment_number value of the last comment created for the same Post object.
I believe doing something like below could lead to a race condition issue:
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()
How can we do this in a thread-safe way that wouldn't lead to a race condition issue?