Difference between auto_now_add and timezone.now as default value
Asked Answered
S

4

12

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.

Supat answered 27/11, 2019 at 16:32 Comment(0)
T
11

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.

Tricostate answered 22/9, 2020 at 7:35 Comment(0)
S
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.

Supat answered 27/11, 2019 at 16:36 Comment(0)
C
0

auto_now=… [Django-doc] and auto_now_add=… [Django-doc] are used to use the timestamp when creating or updating the object. But has some extra implications: it means the field is non-editable, so it does not appear in ModelForms, but even if you would edit the field manually, it will not work, because it does not use the value that has been set, but timezone.now() [GitHub]:

class DateTimeField(DateField):
    # …

    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)

You can also set default=timzone.now(), but then the field is thus still, by default, editable, and you can thus manually set the field on the model object.

Cycloid answered 9/8 at 16:39 Comment(0)
S
-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

Schach answered 27/11, 2019 at 16:39 Comment(2)
I think both will be with TZ. Or not? And why must enter date, I can always use default value?Supat
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.Schach

© 2022 - 2024 — McMap. All rights reserved.