gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:09:45 25 4
gpt4 key购买 nike

我尝试这样的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com