auto_now vs auto_now_add in Django: Key Differences and Usage
auto_now_add sets a field to the current date and time only when the object is first created, while auto_now updates the field to the current date and time every time the object is saved. Use auto_now_add for creation timestamps and auto_now for last-modified timestamps.Quick Comparison
This table summarizes the main differences between auto_now and auto_now_add in Django model fields.
| Feature | auto_now_add | auto_now |
|---|---|---|
| When it sets the date/time | Only once when the object is created | Every time the object is saved |
| Typical use case | Creation timestamp | Last modified timestamp |
| Can be manually changed | No, it is set only once automatically | No, it updates automatically on save |
| Updates on object save | No | Yes |
| Field type | Usually DateTimeField or DateField | Usually DateTimeField or DateField |
Key Differences
auto_now_add automatically sets the field to the current date and time only once when a new record is created. This means the value stays the same even if you update the record later. It is perfect for tracking when an object was first created.
On the other hand, auto_now updates the field to the current date and time every time you save the object. This makes it ideal for tracking the last time the object was modified.
Both options prevent manual editing of the field in forms by default, as Django manages their values automatically. If you want to manually set or change these fields, you should avoid using these options and handle the values yourself.
Code Comparison
from django.db import models class MyModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) # When you create an instance: # my_obj = MyModel.objects.create() # my_obj.created_at is set once and never changes on updates.
auto_now Equivalent
from django.db import models class MyModel(models.Model): updated_at = models.DateTimeField(auto_now=True) # When you save the instance: # my_obj = MyModel.objects.get(id=1) # my_obj.save() # updated_at updates to the current datetime every save.
When to Use Which
Choose auto_now_add when you want to record the exact time an object was created and never change it afterward, such as a creation timestamp.
Choose auto_now when you want to track the last time an object was updated, like a last-modified timestamp.
If you need to manually set or edit these timestamps, avoid using these options and manage the fields yourself.
Key Takeaways
auto_now_add sets the timestamp only once at creation.auto_now updates the timestamp every time the object is saved.auto_now_add for creation dates and auto_now for modification dates.