gpt4 book ai didi

python - Django 批量更新触发 save()

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:47 24 4
gpt4 key购买 nike

我需要重新保存我所有的模型

Users.objects.all().update(active=True)

在模型中:

 def save(self, *args, **kwargs):
self.url = "XYZ"

super(User, self).save(*args, **kwargs)

但是,上述不会触发这些模型上的 save() 方法。所以没有设置 url = XYZ。这可能吗?

更新:

看起来我无法使用 .update() 执行此操作我已经尝试过:

>>> objects = Users.objects.all()
>>> for item in objects:
... item.save()

最佳答案

不,这是 impossible :

Realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()). If you want to update a bunch of records for a model that has a custom save() method, loop over them and call save()

$ ./manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> for u in User.objects.all():
... u.is_active = True
... u.save()
...
>>>

关于python - Django 批量更新触发 save(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324592/

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