代码之家  ›  专栏  ›  技术社区  ›  Prometheus

Django批量更新以触发save()

  •  6
  • Prometheus  · 技术社区  · 11 年前

    我需要重新保存所有模型

    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()
    
    1 回复  |  直到 11 年前
        1
  •  5
  •   catavaran    11 年前

    不,这是 impossible :

    认识到update()在SQL级别进行更新,因此不会在模型上调用任何save()方法,也不会发出pre_save或post_save信号(这是调用Model.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()
    ... 
    >>>