Django:是否有必要在原子事务中为最近创建的对象调用select_for_update?

时间:2017-04-10 18:32:15

标签: django transactions atomic django-orm

我有一个原子事务视图,其中创建了一个对象然后更新:

def buy(request):

    with transaction.atomic():

        # get request.user for update
        user = User.objects.select_for_update().get(id=request.user.id)

        user.order_count += 1

        # get other stuff for update
        items = Item.objects.select_for_update().filter(sold=False)

        items.update(user=user)

        # DO I NEED select_for_update SOMEWHERE HERE FOR NEXT UPDATE?
        new_sell = Sell.objects.create(user=user)

        # some_operations()

        new_sell.some_field = something
        new_sell.save()

        HttpResponse('Done')

在原子事务中没有select_for_update()更新新创建的对象是否安全?

或者普通人在这种情况下如何实施select_for_update?

我想,这将是100%安全的,但看起来不是一个好的计划:

new_sell = Sell.objects.create(user=user)
sell = Sell.objects.select_for_update().get(id=new_sell.id)
# Now we can do everything with sell object

0 个答案:

没有答案