Which timezone does Django use in DateField's auto

How does Django write the date field when the field is marked with auto_now_add attribute?

Is it like datetime.now().date() or timezone.now().date() ?

In other words, which timezone does it use to get the current date?


Looks like it uses datetime.date.today() , which would be the local date of the system:

db/models/fields/__init__.py :

class DateField(Field):
    ...
    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

If you wanted a different behavior you could remove auto_now_add=True then connect the model's pre_save signal to a receiver that would set your field to the date of your choice.

Alternatively, you could override the model's save method and set the field there.


Django by default uses the timezone mentioned in your settings.py TIME_ZONE attribute.

By default it is set to something like:

TIME_ZONE = 'UTC'

More details on its usages could be found here:

https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/

链接地址: http://www.djcxy.com/p/81978.html

上一篇: 无法将列添加到表中

下一篇: Django在DateField的auto中使用哪个时区