#19427: Lacking Documentation on Custom Related Fields Pre-Save Override
--------------------------------+--------------------
     Reporter:  s.shanabrook@…  |      Owner:  nobody
         Type:  Bug             |     Status:  new
    Component:  Documentation   |    Version:  1.4
     Severity:  Normal          |   Keywords:
 Triage Stage:  Unreviewed      |  Has patch:  0
Easy pickings:  1               |      UI/UX:  0
--------------------------------+--------------------
 The process to create a custom field that inherits a `OneToOneField` or a
 `ForeignKey ` (and I assume a `ManyToManyField` as well) and overrides the
 `pre_save` method, is not clear in the documentation.
 [https://docs.djangoproject.com/en/dev/howto/custom-model-fields
 /#preprocessing-values-before-saving The section] that outlines how to
 override the `pre_save` method says that the attribute name is
 `self.attname`, when in fact on a related field, `self.attname` is the
 model's id field for the related object.

 So in order to actually modify the related object and then save it, you
 must do something like this:


 {{{
 #!python
 class CustomRelatedField(ForeignKey):
     def pre_save(self, model_instance, add):
         related_object = getattr(model_instance, self.name)
         # Do stuff with object, custom saving

         id = getattr(related_object, 'id', None)
         setattr(model_instance, self.attname, id)
         setattr(model_instance, self.name, redirect)
         return id
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/19427>
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 post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to