在Django更新查询中使用现有字段值 [英] Using existing field values in django update query

查看:46
本文介绍了在Django更新查询中使用现有字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新表中的一堆行以设置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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆