Temporarily disable auto_now / auto_now_add

后端 未结 12 1213
刺人心
刺人心 2020-12-12 17:49

I have a model like this:

class FooBar(models.Model):
    createtime = models.DateTimeField(auto_now_add=True)
    lastupdatetime = models.DateTimeField(auto         


        
12条回答
  •  生来不讨喜
    2020-12-12 18:25

    You can't really disable auto_now/auto_now_add in another way than you already do. If you need the flexibility to change those values, auto_now/auto_now_add is not best choice. It is often more flexible to use default and/or override the save() method to do manipulation right before the object is saved.

    Using default and an overridden save() method, one way to solve your problem would be to define your model like this:

    class FooBar(models.Model):
        createtime = models.DateTimeField(default=datetime.datetime.now)
        lastupdatetime = models.DateTimeField()
    
        def save(self, *args, **kwargs):
            if not kwargs.pop('skip_lastupdatetime', False):
                self.lastupdatetime = datetime.datetime.now()
    
            super(FooBar, self).save(*args, **kwargs)
    

    In your code, where you want to skip the automatic lastupdatetime change, just use

    new_entry.save(skip_lastupdatetime=True)
    

    If your object is saved in the admin interface or other places, save() will be called without the skip_lastupdatetime argument, and it will behave just as it did before with auto_now.

提交回复
热议问题