Opened 12 years ago

Closed 9 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

Description

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, 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

Change History (7)

comment:1 by s.shanabrook@…, 12 years ago

Needs documentation: set

comment:2 by Russell Keith-Magee, 12 years ago

Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

comment:3 by vijay_shanker, 12 years ago

Owner: changed from nobody to vijay_shanker
Status: newassigned

comment:4 by anonymous, 12 years ago

Owner: changed from vijay_shanker to anonymous

comment:5 by Tim Graham, 11 years ago

Owner: anonymous removed
Status: assignednew

comment:6 by Tim Graham, 11 years ago

Easy pickings: unset
Needs documentation: unset

comment:7 by Tim Graham, 9 years ago

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