Django auto_now vs auto_now_add

Viewed 2811

Problems are encountered if auto_now and auto_now_add are confused. How do auto_now or auto_now_add work?

auto_now : Time will be created every time when use models.save() or models.create() but it doesn't work if you use query.update(), it only updates some data but it does not update date automatically

auto_now_add : Time will be created only the first time when using models.save() or models.create()

How should they be used?

auto_now_add should be used with created_date and auto_now should used with updated_date

created_date = models.DateTimeField(auto_now_add = True)
updated_date = models.DateTimeField(auto_now = True)
1 Answers

To answer your question: how to best use auto_now_add vs auto_now? - Your ideas for using them with DateTimeField or DateField are exactly right!

auto_now_add is perfect for a one-off modification of a field on your model, ONLY when the model instance is created and saved for the first time. As you noted, it is great for a created_at or timestamp field will never need to change again.

auto_now is awesome for whenever you need a field to change anytime the .save() method is called on the model instance. updated_at would be a great opportunity for this, as you mentioned.

The 2 are mutually exclusive, however, as noted in Difference between auto_now and auto_now_add - so don't create a model field and pass both arguments!

Your assumptions were sound; just wanted to confirm them :)

Related