python - 如何在 Django 中批量更新后修改模型?

标签 python django django-models

我尝试这样的代码:

mymodels = MyModel.objects.filter(status=1)
mymodels.update(status=4)
print(mymodels)

结果是一个空列表

我知道我可以使用 for 循环来替换更新。

但是会做很多update query。

在批量更新之后是否仍然可以继续操作 mymodels?

最佳答案

记住 Django's QuerySets are lazy :

QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated

但是the update() method function is actually applied immediately :

The update() method is applied instantly, and the only restriction on the QuerySet that is updated is that it can only update columns in the model’s main table, not on related models.

因此,虽然 - 在您的代码中 - 在您的 filter 之后应用 update 调用,但实际上它是预先应用的,因此您的对象 status 在(延迟)应用 filter 之前被更改,这意味着没有匹配的记录并且结果为空。

关于python - 如何在 Django 中批量更新后修改模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16668639/

相关文章:

带有分页内容的 Django 站点地图

python - 从 QueryDict 中提取项目

python - Connection.queries 返回空列表

django - 合并 django 中带有注释的两个查询集

python - Pymongo - 不允许修改 _id

python - 在 lxml 中定义默认命名空间(无前缀)

python - 在 Ubuntu 14.04 上安装 django-cms

Django 统计当月创建的对象

python - 如何从依赖解析器的输出制作一棵树?

python - Pyephem 本地时间问题