Most Django models have two timestamp fields: created_at to know when a record was created and updated_at for the last edit. The quickest way is auto_now_add=True for created_at and auto_now=True for updated_at — Django fills in both and you never touch them. But these two options have three common "traps": you can't assign an old date when importing data, bulk update() doesn't change updated_at, and the fields are hidden from forms. This post walks through each trap and how to handle it.
The Problem
Suppose you import 500 old posts from another blog and want to keep their original publish dates. You write:
from datetime import datetime from django . utils import timezone
old_date = timezone . make_aware ( datetime ( 2024 , 5 , 10 , 9 , 0 ) )
# Muốn giữ ngày đăng gốc khi import... post = Post . objects . create ( title = "Bài cũ" , created_at = old_date ) print ( post .…