Opened 8 years ago

Closed 5 years ago

#19427 closed Cleanup/optimization (wontfix)

Lacking Documentation on Custom Related Fields Pre-Save Override

Reported by: s.shanabrook@… Owned by:
Component: Documentation Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


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. 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:

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

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

Change History (7)

comment:1 Changed 8 years ago by s.shanabrook@…

Needs documentation: set

comment:2 Changed 8 years ago by Russell Keith-Magee

Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

comment:3 Changed 8 years ago by vijay_shanker

Owner: changed from nobody to vijay_shanker
Status: newassigned

comment:4 Changed 8 years ago by anonymous

Owner: changed from vijay_shanker to anonymous

comment:5 Changed 7 years ago by Tim Graham

Owner: anonymous deleted
Status: assignednew

comment:6 Changed 7 years ago by Tim Graham

Easy pickings: unset
Needs documentation: unset

comment:7 Changed 5 years ago by Tim Graham

Resolution: wontfix
Status: newclosed

Not sure what to do here as attname isn't referenced in the linked doc (maybe it's since been removed). This seems in the realm of private API anyway.

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