The environment
- Django 2.2
- Mysql 5.7
The problem
Regardless of how the time format is set, the database field is saved in microseconds (my requirement is to remove microseconds), as shown in the following figure
# Define fields in models
exetime = models.DateTimeField(auto_now_add=True,verbose_name='Execution time')
Copy the code
A modification to setings.py was tried during the session
DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"
L10N=False
USE_TZ=False
Copy the code
I also tried modifying the Model directly
# This should be available below mysql5.6
import datetime
exetime = models.DateTimeField(auto_now_add=datetime.datetime.now().strftime('%Y-%m-%d %H:%I:%S'),verbose_name='Execution time')
Copy the code
None of the above is feasible
To solve
Djangos default datetime(6) to mysql5.7, so the database must contain microseconds. The first option is to change the default mapping to datetime, and the second option is to manually change the corresponding database field
I use the second method to manually change the database field to datetime to satisfy the requirement
To use the first option, check out this file: Django \db\backends\mysql\base.py
class DatabaseWrapper(BaseDatabaseWrapper) :
vendor = 'mysql'
display_name = 'MySQL'
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'integer AUTO_INCREMENT'.'BigAutoField': 'bigint AUTO_INCREMENT'.'BinaryField': 'longblob'.'BooleanField': 'bool'.'CharField': 'varchar(%(max_length)s)'.'DateField': 'date'.'DateTimeField': 'datetime(6)'.The default value is 6
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)'.'DurationField': 'bigint'.'FileField': 'varchar(%(max_length)s)'.'FilePathField': 'varchar(%(max_length)s)'.'FloatField': 'double precision'.'IntegerField': 'integer'.'BigIntegerField': 'bigint'.'IPAddressField': 'char(15)'.'GenericIPAddressField': 'char(39)'.'NullBooleanField': 'bool'.'OneToOneField': 'integer'.'PositiveIntegerField': 'integer UNSIGNED'.'PositiveSmallIntegerField': 'smallint UNSIGNED'.'SlugField': 'varchar(%(max_length)s)'.'SmallIntegerField': 'smallint'.'TextField': 'longtext'.'TimeField': 'time(6)'.'UUIDField': 'char(32)',}Copy the code