home ~ projects ~ socials

Create An Automatic DateTimeField In Django

File: SITE_NAME/APP_NAME/models.py

from django.db import models

class Note(models.Model):
    note_text = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.note_text

Notes

  • auto_not_add=True sets the datetime when the object is first created
  • auto_now=True updates the datetime every time the object is saved with .save()
  • Note that auto_now=True won't update using approaches other than .save() (e.g. QuerySet.update() won't work)
-- end of line --

References

  • Note that DateTimeField is below it but it makes references to options that are in the DateField.