【问题标题】:how django 'auto_now' ignore the update of specified fielddjango 'auto_now' 如何忽略指定字段的更新
【发布时间】:2016-11-02 21:25:30
【问题描述】:

我有一个模型,像这样:

    name = models.CharField(max_length=255)
    modify_time = models.DateTimeField(auto_now=True)
    chasha = models.CharField(max_length=255)
    stat = models.CharField(max_length=255)

通常,当我更新 'name'、'chasha'、'stat' 字段时,'modify_time' 将被更新。但是,我只是不想在更新“stat”时更新“modify_time”。我该怎么做?

谢谢。

【问题讨论】:

    标签: python sql django model


    【解决方案1】:

    使用自定义保存方法通过查看以前的实例来更新字段。

    from django.db import models
    from django.utils import timezone as tz
    
    
    class MyModel(models.Model):
        name = models.CharField(max_length=255)
        modify_time = models.DateTimeField(null=True, blank=True)
        chasha = models.CharField(max_length=255)
        stat = models.CharField(max_length=255)
    
        def save(self, *args, **kwargs):
            if self.pk: # object already exists in db
                old_model = MyModel.objects.get(pk=self.pk)
                for i in ('name', 'chasha'): # check for name or chasha changes
                    if getattr(old_model, i, None) != getattr(self, i, None):
                        self.modify_time = tz.now() # assign modify_time
            else: 
                 self.modify_time = tz.now() # if new save, write modify_time
            super(MyModel, self).save(*args, **kwargs) # call the inherited save method
    

    编辑:像上面一样从modify_time中删除auto_now,否则会在save方法中设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2020-09-02
      • 1970-01-01
      • 2019-12-31
      相关资源
      最近更新 更多