Auto_now vs Auto_now_add in Django Date Time Fields

Learn about auto_now vs auto_now_add in Django Date Time Fields

Picture of Nsikak Imoh, author of Macsika Blog
White image with the text auto_now vs auto_now_add in Django Date Time Fields
White image with the text auto_now vs auto_now_add in Django Date Time Fields

This post is part of the tutorial series titled Learn to Use Django with FastAPI Frameworks

Table of Content

There are two useful properties that can be used
in Django's DateTimeField and DateField.

These properties are responsible for automatically managing date and time.

They are useful in keeping track of when a specific instance is created or updated.

This saves you a lot of extra code and time taken to do this manually.

All you need to do to automatically set the date and time field is to simply set the auto_now and auto_now_add arguments to True.

Check out the following example:

class RegisterBooklet(models.Model):
    description = models.CharField(max_length=255)
    status = models.CharField(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
Highlighted code sample.

Difference Between auto_now vs auto_now_add in Django

The auto_now_add will set the only when the instance is created.

created_at = models.DateTimeField(auto_now_add=True)
Highlighted code sample.

On the other hand, 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

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

Wrap Off

There you have it! I hope you found this post useful somehow.

If you have any questions or need clarification, feel free to reach out to me.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Get the Complete Code of Django and FastAPI Combo Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?