pythondjangodjango-modelsdjango-formsdjango-templates

Difference between auto_now and auto_now_add


What I understood in Django models field's attributes is

My question is what if a field in model contains both the auto_now and auto_now_add set to True? What happens in that case?


Solution

  • auto_now takes precedence (obviously, because it updates field each time, while auto_now_add updates on creation only). Here is the code for DateField.pre_save method:

    def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = datetime.date.today()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super().pre_save(model_instance, add)
    

    As you can see, if auto_now is set or both auto_now_add is set and the object is new, the field will receive current day.

    The same for DateTimeField.pre_save:

    def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = timezone.now()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super().pre_save(model_instance, add)