django - 在 Django 更新查询中使用现有字段值

标签 django django-models

我想更新表中的一堆行以设置 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 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 - 在 Django 更新查询中使用现有字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337619/

相关文章:

python - Django 查询集 'in' 运算符在第一次调用时失败

python - 是否可以对 OuterRef 表达式进行算术运算?

django - 使用 Django Treebeard 获取祖先时如何防止 N+1 查询?

django - django中业务逻辑放在哪里

django - 如何对 FileField 内容使用验证器

python - 在 Django 中,如何遍历父模型(用户)中的特定字段,包括附加子模型(用户配置文件)中的一些特定字段

android - 来自 Django/Python 应用程序的智能手机警报

Tiwsted : Twisted requires zope. 接口(interface) 3.6.0 的 Django 错误

python - Django 登录重定向到密码重置页面而不是个人资料页面

django - 如何将实际图像文件从一个模型复制到另一个模型?