10

What is the difference between auto_now_add and timezone.now (as default value) for models in Django? Example:

create_date = models.DateTimeField(auto_now_add=True)

and

create_date = models.DateTimeField(default=timezone.now)

?

UPD. I'm talking about the case when I always not overriding default value.

wowkin2
  • 5,895
  • 5
  • 23
  • 66

3 Answers3

10

default supplies a default value for when an instance is being saved without a value for the field, but still implies that the field is user-editable, so someone could input a value for the field.

auto_now and auto_now_add imply the field is not user-editable and must always get set to this value.

Someone posted this on reddit.

wowkin2
  • 5,895
  • 5
  • 23
  • 66
Maran Sowthri
  • 829
  • 6
  • 14
1

Looks like Django does the same timezone.now() under the hood, on 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(DateTimeField, self).pre_save(model_instance, add)

The only difference is the moment when python will call timezone.now(), but that should be nano-seconds difference.

wowkin2
  • 5,895
  • 5
  • 23
  • 66
-1

Explanation:

auto_now_add=True will create date on save model

default=timezone.now will be default date with timezone and you must enter date with timezone

Link to explanation: DateModel

Marin
  • 1,098
  • 14
  • 33
  • I think both will be with TZ. Or not? And why `must enter date`, I can always use default value? – wowkin2 Nov 27 '19 at 16:42
  • You don't have blank=True, null=True on that field so it can't be bypassed by default. Django will save datetime with default timezone.now in every save method. – Marin Nov 27 '19 at 17:44