The Python Oracle

Difference between auto_now and auto_now_add

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Difference Between Auto_now And Auto_now_add
00:31 Accepted Answer Score 66
01:13 Answer 2 Score 9
01:29 Answer 3 Score 6
01:45 Answer 4 Score 11
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/5138...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangomodels #djangoforms #djangotemplates

#avk47



ACCEPTED ANSWER

Score 66


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)



ANSWER 2

Score 11


These fields are built into Django for expressly this purpose — auto_now fields are updated to the current timestamp every time an object is saved and are therefore perfect for tracking when an object was last modified, while an auto_now_add field is saved as the current timestamp when a row is first added to the database and is therefore perfect for tracking when it was created.




ANSWER 3

Score 9


According to the django documentation using both auto_now and auto_now_add in your model fields as True will result in an error because they are both mutually exclusive.




ANSWER 4

Score 6


As Official Django documentation says -

auto_now, auto_now_add and default are mutually exclusive and will result in an error if used together