Menu

Django: Use auto_now and auto_now_add Correctly — When to Switch to default=timezone.now
📰

Django: Use auto_now and auto_now_add Correctly — When to Switch to default=timezone.now

DEV Community: django·Linh Fish Dev·1 day ago
#1MmHE4Id
#devtodjango#devto#dev#django#update
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.