我有一个线程评论系统,在 99.9% 的时间里都可以正常工作,但偶尔树会崩溃,左/右值会重复。
我发现当两个帖子同时发生时(彼此相隔不到一秒)会发生这种情况,并且大概发生的情况是第二个帖子在第一个之前更新树的左/右值完成了。
我在 views.py
中的评论插入代码如下:
@login_required
@transaction.autocommit
def comment(request, post_id):
parent = get_object_or_404(Post, pk=post_id)
if request.method == 'POST':
form = PostForm(request.POST)
form.parent = post_id
if form.is_valid():
new_post = newPost(request.user, form.cleaned_data['subject'], form.cleaned_data['body'])
new_post.insert_at(parent, 'last-child', save=True)
return HttpResponseRedirect('/posts/')
else:
form = PostForm()
return render_to_response('posts/reply.html', {'requestPost': request.POST, 'form': form, 'parent': parent}, context_instance=RequestContext(request))
处理这个问题的正确方法是什么?有没有一种 django 方法可以确保在第一个数据库事务完成之前不会调用第二个 View ?或者我应该在每次插入后重建树以确保完整性?或者是否有更好的插入方法可供使用?
谢谢!
编辑:我正在使用 MySQL。
最佳答案
transaction.autocommit() 是标准的 django 行为。如果没有重新定义全局事务行为,你的装饰器什么都不做。 使用应该使用 commit_on_success() 装饰器。 View 中的所有数据库操作都将在一个事务中。 您可以在 https://docs.djangoproject.com/en/1.5/topics/db/transactions/ 上阅读更多内容
PS:django 1.6 中事务管理会更新,注意。
关于python - django-mptt:处理并发插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19593781/