Python 如何使用 select_for_update 在 Django 中“获取”查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17159471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:38:28  来源:igfitidea点击:

How to use select_for_update to 'get' a Query in Django?

pythondjangodjango-queryset

提问by Indradhanush Gupta

As the Django Documentation says, select_for_updatereturns a Queryset. But getdoes not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing something like:

正如 Django 文档所说,select_for_update返回一个Queryset. 但get没有。现在我有一个查询,我确信它只会返回一个元组。但是我也需要为这个事务获取锁。所以我正在做类似的事情:

ob = MyModel.objects.select_for_update().filter(some conditions)

Now I need to modify some values of ob. But ob is a Queryset. This seems pretty simple, but beats me. I'm pretty new to Django. Some advice please.

现在我需要修改 ob 的一些值。但是 ob 是一个Queryset. 这看起来很简单,但打败了我。我对 Django 很陌生。请给一些建议。

采纳答案by Yuji 'Tomita' Tomita

Just call get, slice it, etc. and save as usual. The lock is in place through the transaction.

只需调用get,切片等,然后像往常一样保存。锁定通过事务就位。

ob = MyModel.objects.select_for_update().get(pk=1)

Any changes are committed at the end of the transaction (which by default through 1.5 is per-request)

任何更改都在事务结束时提交(默认情况下通过 1.5 是每个请求)

回答by Omid Raha

You canalso use select_for_updatewith get_object_or_404function:

可以使用select_for_updatewithget_object_or_404函数:

from django.db import transaction
from django.shortcuts import get_object_or_404

with transaction.atomic():
    obj = get_object_or_404(MyModel.objects.select_for_update(), pk=pk)
    # do some stuff with locked obj