Both Django’s DateTimeField
and DateField
have two very useful arguments for automatically managing date and time.
If you want keep track on when a specific instance was created or updated you don’t need to do it manually: just set
the auto_now
and auto_now_add
arguments to True
like in the following example:
The auto_now_add
will set the timezone.now()
only when the instance is created, and auto_now
will update the
field everytime the save
method is called.
It is important to note that both arguments will trigger the field update event with timezone.now()
, meaning when
you create an object, both created_at
and updated_at
will be filled.
This is a very simple trick that will make your codebase cleaner.