简体   繁体   中英

Unable to set default vale of DateTimeField to “0000-00-00 00:00:00”

fld_date_time = models.DateTimeField(db_column='FLD_DATE_TIME', blank=True, null=True, default="0001-00-00 00:00:00")

This field in models.py throws error as:

["'0000-00-00 00:00:00' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."]

How to add the default value in django?

Well the problem is that your default value makes no sense. There is no zero-th day, nor is there a zero-th month. The smallest date Python can represent as a datetime object is:

>>> datetime.min
datetime.datetime(1, 1, 1, 0, 0)

so January 1st, 1. In some (most) databases, the range is even more restrictive. For example in MySQL the range is:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31' .

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' .

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC .

It is true that MySQL has a "zero date":

Invalid DATE , DATETIME , or TIMESTAMP values are converted to the "zero" value of the appropriate type ( '0000-00-00' or '0000-00-00 00:00:00' ).

But there is no good way to wrap this to the datetime object, since as said before, it is out of the representable range.

You can use a solution proposed here that basically constructs a new Django ZeroDateTimeField to map None on this zero value. But you can, to the best of my knowledge, not do this with a standard DateTimeField .

You thus either can use the minimum representable datetime object representable by your database, or use NULL instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM