👋
Welcome to my blog!

Django automatic date time fields - created_on and updated_on

Automatically handling date and time fields

Django automatic date time fields - created_on and updated_on
Django

Published At

7/3/2021

Reading Time

~ 1 min read

In Django, DateTimeField and DateField have two very useful arguments for automatically handling date and time fields. You don't need to keep track of creation and updation of data manually. Just set the auto_now and auto_now_add arguments to True like in the following example:

python
class BaseMode(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
 
		class Meta:
		    abstract = True
python
class BaseMode(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
 
		class Meta:
		    abstract = True

The auto_now_add will set the timezone.now() only when the instance is created, and auto_now will update the field every time the save method is being called on model.

And at the time of creation of instance, both will be filled.

✌️

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Join My Exclusive Newsletter Community

Step into a world where creativity intersects with technology. By subscribing, you'll get a front-row seat to my latest musings, full-stack development resources, and exclusive previews of future posts. Each email is a crafted experience that includes:

  • In-depth looks at my covert projects and musings to ignite your imagination.
  • Handpicked frontend development resources and current explorations, aimed at expanding your developer toolkit.
  • A monthly infusion of inspiration with my personal selection of quotes, books, and music.

Embrace the confluence of words and wonder, curated thoughtfully and sent straight to your inbox.

No fluff. Just the highest caliber of ideas.