Forums

DateTimeField auto_now_add=True but empty

Hi All,

I added the following models with auto_now_add and auto_now = True.

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

However, after makemigrations and migrate, both fields remains empty when i insert a new row.

I found both created_at and updated_at are not created with auto NOW().

mysql> DESCRIBE API_vehicle;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| vehicle_no | varchar(16)  | NO   | UNI | NULL    |                |
| created_at | datetime(6)  | NO   |     | NULL    |                |
| updated_at | datetime(6)  | NO   |     | NULL    |                |

Is this a bug or I miss some step ? Appreciate help. Thanks.

How do you insert rows?

I did the following : INSERT INTO API_vehicle(vehicle_no) VALUES ('QAA 4248 V');

If you're inserting using SQL, then the auto_add logic in the model is not executed. If you add your records using the ORM, then the model code to add the time stamps will be executed.