Skip to content
Advertisement

how django ‘auto_now’ ignore the update of specified field

i have a model, like this:

    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 ‘name’, ‘chasha’, ‘stat’ field. But, I just did not want the ‘modify_time’ been updated when i update ‘stat’. how can i do that?

thanks.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement