Post Image

Django auto_now and auto_now_add How They Work

When working with databases often times you need to save the date and time objects were created and last modified, Django ORM makes this very easy once you understand how auto_now and auto_now_add works. It is fairly intuitive but in this article I will be demonstrating how it works.

 

Example Model

Below I have constructed an example model that has 2 datetime fields, one for tracking when the object was created, the other for when the object was modified.

from django.db import models

# Create your models here.

class Node(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)

Not too make this post too short, that is literally all the code that needs to be in place for tracking the date and time an object was created and the date and time an object was last modified.

 

How Does it Work

In the Django ORM when you set auto_now_add to True when a new object is saved for the first time it will get the date and time at that moment and save it to the field in the database. When auto_now is set to True each time the object is saved, including the first time it will get the current date and time and save it in that field.

Using these built in arguments you can reduce the code that you have to write and maintain for common database tasks like this. If you have questions please leave a comment below!



Comments (0)
Leave a Comment