Home > Blockchain >  Django Models auto_now saving same time as auto_now_add
Django Models auto_now saving same time as auto_now_add

Time:08-05

Django models issue. I add these 2 fields in almost every model to store created (auto_now_add=True) and updated datetime (auto_now=True).

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

Problem

Problem is when I create a new row in a table using Django, created_at field gets populated with current datetime (which is fine) but its updated_at field also gets populated on first time creation.

Does that make sense? From an end user's point of view, I only created a record but never updated it but in database its updated time is also updated since data is inserted first time in a row (happens whenever you insert a new row). So, when a user views the record, system will show created_at and updated_at exactly same.

CodePudding user response:

TL;DR: when you create an object for the first time, both created_at and updated_at will be filled with values, accordingly to the code you crafted.

  • The auto_now_add will set the timezone.now() only when the instance is created.
  • The auto_now will update the field every time the save method is called.

However, both functions the same way by triggering the field update event with timezone.now().

This means that when you create an object for the first time, both created_at and updated_at will be filled with values.

But, the next time you save that object, the created_at will remain the same, while the updated_at will call the timezone.now().

The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.

Django docs: https://docs.djangoproject.com/en/4.0/ref/models/fields/

  • Related