[PYTHON] Django's auto_now may not be updated

Django's model has a DateTimeField as its argument

--ʻAuto_now_add: Enter the current time when creating --ʻAuto_add: Update with the current time when saving

There is a convenient function called. Often

class User(models.Model):
     name = models.CharField()
     created = models.DateTimeField(
        auto_now_add=True
     )
     updated = models.DateTimeField(
        auto_now=True
     )

It is defined and used in the form of.

Updated with auto_now

With a model with such a field

user = User.objects.create(name="kasajei")
print(user.created)
>>>Current time
print(user.updated)
>>>Current time
user.name = "kasajei2"
user.save()
print(user.updated)
>>>Saved time

Then, set the current time in updated, and Django will update it with a value without saving. Convenient!

Auto_now, but not updated

However, sometimes, if I thought that it would not be updated, it seems that it will not be updated in the case of specifying the argument with ʻupdate` as follows.

user.name="kasajei3"
user.save(update_fields="name")
print(user.updated)
>>>Not updated! !!

Other,

User.objects.filter(name="kasajei").update(name="kasajei2")
user = User.objects.get(name="kasajei2")
print(user.updated)
>>>Not updated! !!

Etc. will not be updated!

As you can see from the properly issued SQL, I trusted ʻauto_now` too much and didn't notice it for a while.

Since it's ʻauto_now`, I'm wondering if it's okay to update it, but what about it?

Recommended Posts

Django's auto_now may not be updated
[django] model mods may or may not be updated
Choices not updated in Django's Multiple Choice Field
PyQtGraph may not be available in the interpreter.
Qiitadon icon may not be changed by API