Opened 6 years ago

Closed 6 years ago

Last modified 2 years ago

#30319 closed Uncategorized (wontfix)

model.save() surprising behavior with update_fields specified and auto_now field in model

Reported by: sebhaase Owned by: nobody
Component: Database layer (models, ORM) Version: 2.1
Severity: Normal Keywords:
Cc: seb.haase+django@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In section "Specifying which fields to save" (https://docs.djangoproject.com/en/dev/ref/models/instances/#specifying-which-fields-to-save) it reads that update_fields can be specified mostly for performance benefits...

However, I found that regarding a field with auto_now=True there is a different outcome.
IOW, specifying update_fields can be used to keep the old date in respective "auto_now=True"-field UNLESS that field is also explicitly given un update_fields

This should be more prominently stated in the documentation.

In addition I also noticed that - using deserialization - object.save() gives unexpected different results for auto_now field:

  • if the object-pk already exists , the field is saved as given
  • but if it does not exist, the given value is ignored, and the current time is used instead

... very strange if you ask me...

refs:
https://stackoverflow.com/questions/17474057/enforce-auto-now-when-using-saveupdate-fields
https://groups.google.com/d/msg/django-users/sqMrUlZP2-8/FczIEwwMBAAJ

Change History (4)

comment:1 by Mariusz Felisiak, 6 years ago

Resolution: invalid
Status: newclosed

It sounds quite clear for me that if you add fields with auto_now flag to the list of updated_fields then its value will be updated. Due to the different behavior with and without PK please check how-django-knows-to-update-vs-insert. IMO documentation doesn't require clarification here.

If you have other support questions please see TicketClosingReasons/UseSupportChannels for ways to get help with Django usage (and yes I've seen that you've already posted on django-users).

comment:2 by Mariusz Felisiak, 6 years ago

Resolution: invalidwontfix

comment:3 by sebhaase, 6 years ago

I would still suggest to rephrase:
"There will be a slight performance benefit from preventing all of the model fields from being updated in the database."
to
"There will be a slight performance benefit from preventing all of the model fields from being updated in the database. Note that auto_now=True fields will be stay untouched unless explicitly listed in update_fields."

I'm sure I'm not the only who got tripped by this - otherwise the docs of django a really superb!

comment:4 by Nick Pope, 2 years ago

This behaviour is now documented, see the PR.

Note: See TracTickets for help on using tickets.
Back to Top