我想更新表中的一堆行以设置 id = self.id。我将如何执行以下操作?
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
最佳答案
您可以使用 F expression 执行此操作:
from django.db.models import F
tasks = Task.objects.filter(task_definition__cascades=False)
.update(shared_task_id=F('id'))
您可以使用 F
执行的操作有一些限制update
中的对象调用,但在这种情况下它会正常工作:Calls to update can also use
F expressions
to update one field based on the value of another field in the model.However, unlike
F()
objects infilter
andexclude
clauses, you can’t introduce joins when you useF()
objects in anupdate
– you can only reference fields local to the model being updated. If you attempt to introduce a join with anF()
object, aFieldError
will be raised[.]
https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once
关于django - 在 Django 更新查询中使用现有字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337619/