Django 和 Django ORM:批量更新记录的性能改进

Django & Django ORM: performance improvements to bulk updating records

我希望这将是一个非常简单的问题。

我只是想要一些关于批量更新记录的建议。

批量更新示例可能如下所示:

for user in User.objects.all().iterator():
    user.is_active = False
    user.save()

是否有更有效的方法使用 Django ORM 在数据库级别执行此操作?

以下是否更有效:

User.objects.all().update(is_active=False)?

是的,使用 update 会更有效率。这将执行一个数据库调用,而不是每个对象一个。

。您可以使用 User.objects.all().update(is_active=False).

这将导致 单个 查询,如下所示:

UPDATE `auth_user`
SET `is_active` = 0

它将因此减少到数据库的往返次数到一次

它会起作用,但请注意,更新命令将直接转换为 SQL 命令,没有 运行 您在 save 上自定义的任何内容,也不会触发保存信号.如果你的情况没有问题,而且你更担心性能,那就去吧。

来自 django 文档:

Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn’t run any save() methods on your models, or emit the pre_save or post_save signals (which are a consequence of calling save()), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that the save() method is called on each instance, you don’t need any special function to handle that.

https://docs.djangoproject.com/en/2.2/topics/db/queries/#updating-multiple-objects-at-once