在Django更新查询中使用现有字段值 [英] Using existing field values in django update query
问题描述
我想更新表中的一堆行以设置id =self.id.我该怎么办?
I want to update a bunch of rows in a table to set the id = self.id. How would I do the below?
from metadataorder.tasks.models import Task
tasks = Task.objects.filter(task_definition__cascades=False)
.update(shared_task_id=self.id)
等效的SQL将是:
update tasks_task t join tasks_taskdefinition d
on t.task_definition_id = d.id
set t.shared_task_id = t.id
where d.cascades = 0
推荐答案
您可以使用对于在 update
调用中使用 F
对象可以执行的操作有一些限制,但是在这种情况下可以很好地工作:
There are some restrictions on what you can do with F
objects in an update
call, but it'll work fine for this case:
更新调用还可以使用
F表达式
根据模型中另一个字段的值来更新一个字段.
Calls to update can also use
F expressions
to update one field based on the value of another field in the model.
但是,与 filter
和 exclude
子句中的 F()
对象不同,使用 F时不能引入联接()
在 update
中的对象–您只能引用要更新的模型本地的字段.如果尝试使用 F()
对象引入联接,则会引发 FieldError
.[.]
However, unlike F()
objects in filter
and exclude
clauses, you can’t introduce joins when you use F()
objects in an update
– you can only reference fields local to the model being updated. If you attempt to introduce a join with an F()
object, a FieldError
will be raised[.]
https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once
这篇关于在Django更新查询中使用现有字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!