#29173: Document that Model.save() doesn't refresh fields from the database
--------------------------------------+------------------------------------
     Reporter:  Xtreak                |                    Owner:  nobody
         Type:  Cleanup/optimization  |                   Status:  closed
    Component:  Documentation         |                  Version:  2.0
     Severity:  Normal                |               Resolution:  invalid
     Keywords:                        |             Triage Stage:  Accepted
    Has patch:  0                     |      Needs documentation:  0
  Needs tests:  0                     |  Patch needs improvement:  0
Easy pickings:  0                     |                    UI/UX:  0
--------------------------------------+------------------------------------
Changes (by Carlton Gibson):

 * status:  new => closed
 * resolution:   => invalid


Comment:

 The ''Custom Model Fields'' How-To discusses this usage explicitly in the
 [https://docs.djangoproject.com/en/2.0/howto/custom-model-fields
 /#preprocessing-values-before-saving Preprocessing values before saving]
 section.

 It suggests using `pre_save(model_instance, add)` for this kind of
 behaviour.

 It explicitly makes updating the model's attribute the user's
 responsibility:

 > You should also update the model’s attribute if you make any changes to
 the value so that code holding references to the model will always see the
 correct value.

 Note `pre_save` takes the `model_instance` parameter precisely for this
 purpose.

 The canonical example of this usage is from `DateTimeField`, for handling
 `auto_now` and `auto_now_add`:

 {{{
     def pre_save(self, model_instance, add):
         if self.auto_now or (self.auto_now_add and add):
             value = datetime.date.today()
             setattr(model_instance, self.attname, value)
             return value
         else:
             return super().pre_save(model_instance, add)
 }}}

 The quoted line from the docs was
 
[https://github.com/django/django/commit/8216abe74889cc867a4cf89e6708f37cec6b2e72
 introduced in 2007] so this behaviour (and expected usage) is part of the
 original design of the `Field` API. As such I'm going to close this
 ticket.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/29173#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/067.de29a1a845c7adba728993bb44034186%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to