I have a self-referential ForeignKey field:
class Thing(models.Model)
special_thing = models.ForeignKey(
'self',
blank=True,
null=True
)
On the "Add Thing" form, in addition to other existing things I need to offer a choice "this thing itself", i.e. the Thing which hasn't been added yet. Telling users to Add and then revisit that field is not an option.
How should I go about this?
My current thought is to override the form:
- change "special_thing" from being the default ModelChoiceField to ChoiceField
- add new special ("marker") choice "*** THIS THING ***" to the field's choices in __init__()
- provide clean_special_thing() which allows either "*** THIS THING ***" or the id of a Thing that can be looked up from the queryset.
- In save(), if "*** THIS THING ***" was the choice, save Thing with special_thing=None, afterwards set it to itself and save again. Otherwise look up the Thing by the given id and save as usual.
I'm doing this for the ModelForm of a ModelAdmin. Is there an easier way?