0

Suppose I have a Django app backed by Postgres, and in that app I have model called Contact with a DateTimeField called last_updated. Suppose last_updated has auto_now set to True.

I know there are some circumstances in which last_updated will not get updated when a Contact record is updated:

  • Contact.objects.filter(xxx).update(yyy) will not update last_updated unless last_updated is included in yyy
  • Contact.objects.bulk_update(contacts_qs, [zzz]) will not update last_updated unless last_updated is in zzz

Are there other ways to update modify Contact objects (barring accessing the DB directly) where last_updated won't be updated?

stranger
  • 390
  • 4
  • 17

1 Answers1

1

From the docs auto_now:

DateField.auto_now

Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

So unless you are doing an unmodified save directly from the model, it is possible the field will not be automatically saved. This is why I use a Postgres trigger/function combination that handles this in the database. Also to handle data updates coming from outside Django.

Adrian Klaver
  • 15,886
  • 2
  • 17
  • 28
  • Thank you for your input. I'm not very fluent with Postgres triggers and functions, would this be a good SO question to start from: https://stackoverflow.com/questions/1035980/update-timestamp-when-row-is-updated-in-postgresql – stranger Nov 10 '21 at 17:41
  • Yes, that is essentially what I do. – Adrian Klaver Nov 10 '21 at 18:17