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, 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)
Triage Stage: |
Unreviewed → Accepted
|
Type: |
Bug → Cleanup/optimization
|
Owner: |
changed from nobody to vijay_shanker
|
Status: |
new → assigned
|
Owner: |
changed from vijay_shanker to anonymous
|
Owner: |
anonymous removed
|
Status: |
assigned → new
|
Easy pickings: |
unset
|
Needs documentation: |
unset
|
Resolution: |
→ wontfix
|
Status: |
new → 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.