Auto Timestamp Fields

A snippet showing how to add created_at and updated_at fields in Django models.


# models.py

from django.db import models

class Article(models.Model):
    title = 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.title
  

# models.py (abstract base)

from django.db import models

class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Post(TimeStampedModel):
    title = models.CharField(max_length=200)
  

# Django Shell

>>> from blog.models import Article
>>> a = Article.objects.create(title='Hello')
>>> a.created_at is not None
True
>>> a.save()
>>> a.updated_at <= timezone.now()
True
  
Explanation:
  • auto_now_add sets the timestamp once when the object is created (good for created_at).
  • auto_now updates the field on every save (good for updated_at).
  • Use an abstract base like TimeStampedModel to reuse these fields across multiple models.
  • These fields are managed by Django; you typically don't set them manually.
  • Category Models & ORM
  • Total Views 1000
  • Last Modified 28 December, 2025
  • Tags #models #fields #timestamp #orm
Next snippet
Custom Model Manager
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.