Django

Django automatic date time fields - created_on and updated_on

Automatically handling date and time fields
A corgi smiling happily

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:

1class BaseMode(models.Model):
2 created_at = models.DateTimeField(auto_now_add=True)
3 updated_at = models.DateTimeField(auto_now=True)
4
5 class Meta:
6 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 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.