Home > Enterprise >  What's the diffrence bettwen timezone.now and auto_now_add parameters in DateTimeField field in
What's the diffrence bettwen timezone.now and auto_now_add parameters in DateTimeField field in

Time:11-16

I'm writing my first Django app - blog. When creating Post model I'm asked to create publish and created fields with timezone import.

publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)

It's explained that "By using auto_now_add, the date will be saved automatically when creating an object" and "timezone.now returns the current datetime in a timezone-aware format".

So it seems to me that they both same job. Why not use default=timezone.now in both fields? What's the difference? It's my first question so sorry in advance if I made some mistakes.

CodePudding user response:

They are the same, except for one thing: auto_now_add=True overrides any initial value you pass when creating the object, whereas default=timezone.now will allow you to set your own, different value.

You can read it in the docs

CodePudding user response:

The auto_now_add will set the timezone.now() only when the instance is created, and auto_now will update the field every time the save method is called.

default=timezone.now means setting the default current time when you add or modify a field for a model that already exists, since there can be records in the database, and you need to specify what to fill in for these existing records. Thanks!

  • Related