python / beginner
Snippet
Automatic Creation and Update Timestamps
By using auto_now_add and auto_now, Django automatically manages timestamps for when a record is created and whenever it is updated.
snippet.py
1
2
3
class Post(models.Model):created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)
django
Breakdown
1
created_at = models.DateTimeField(auto_now_add=True)
Automatically sets the field to the current date and time when the object is first created.
2
updated_at = models.DateTimeField(auto_now=True)
Automatically updates the field to the current date and time every time the object is saved.