Opened 3 years ago

Closed 4 months 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 3 years ago by s.shanabrook@…

  • Needs documentation set
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 3 years ago by russellm

  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from Bug to Cleanup/optimization

comment:3 Changed 3 years ago by vijay_shanker

  • Owner changed from nobody to vijay_shanker
  • Status changed from new to assigned

comment:4 Changed 3 years ago by anonymous

  • Owner changed from vijay_shanker to anonymous

comment:5 Changed 2 years ago by timo

  • Owner anonymous deleted
  • Status changed from assigned to new

comment:6 Changed 2 years ago by timo

  • Easy pickings unset
  • Needs documentation unset

comment:7 Changed 4 months ago by timgraham

  • Resolution set to wontfix
  • Status changed from new to closed

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