Search code examples
pythondjangomodel

How to make 'auto_now' ignore the update of specific field


I have this model:

    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)

Usually, modify_time will be updated when I update any of the name, chasha, or stat fields. But I do not want the 'modify_time' to be updated when I update 'stat'. How can I do that?


Solution

  • Use a custom save method to update the field by looking at a previous instance.

    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
    

    Edit: remove auto_now from modify_time like above, otherwise it will be set at the save method.