Understanding Django’s auto_now and auto_now_add features

Posted by

Django auto_now and auto_now_add

Django auto_now and auto_now_add

In Django, the auto_now and auto_now_add options are used to automatically update the date and time fields in a model when a new record is created or when a record is updated. Let’s take a closer look at how these options work:

auto_now

The auto_now option is used to update the date and time fields to the current date and time whenever a record is saved or updated. This option is useful for fields that need to be constantly updated, such as the last modified date of a record. Here’s an example of how to use auto_now in a Django model:

  
  from django.db import models

  class MyModel(models.Model):
      created_at = models.DateTimeField(auto_now=True)
  
  

With this setup, the created_at field will be automatically updated to the current date and time whenever a new record is created or when an existing record is updated.

auto_now_add

The auto_now_add option is used to set the date and time fields to the current date and time when a record is created, but it will not update the field when the record is updated. This option is useful for fields that need to reflect the initial creation date of a record. Here’s an example of how to use auto_now_add in a Django model:

  
  from django.db import models

  class MyModel(models.Model):
      created_at = models.DateTimeField(auto_now_add=True)
  
  

With this setup, the created_at field will be set to the current date and time when a new record is created, but it will not be updated when the record is updated.

By using the auto_now and auto_now_add options in Django models, you can easily manage and update date and time fields without having to manually update them every time a record is saved or created.