I have two models with a foreign key relationship between them. In the admin, the edit page for the model with the foreign key relationship described (Model No. 1) displays a ModelChoiceField. The page for the other side of the relationship (Model No. 2) displayed nothing, until I added the first model to the ModelAdmin as an inline. The inline gives me the option of creating a new object from Model No. 1.
I want to add a ModelChoiceField to the inline on Model No. 2 so that users can choose between creating a new object or selecting from a list of pre-existing ones.
Ideally, I would also be able to use a filter to populate the new ModelChoiceField for Model No. 1 objects.
Okay, asking this question got me nothing but the cool tumbleweed badge for my profile. I eventually discovered the following solution. It’s simpler than I expected but it left me asking another question here because, once implemented, selecting from the ModelChoiceField on the admin page and saving does not create the foreign key relationship as expected.
Anyway, on the the solution:
My Art model contains the boolean field “has_storypak” to indicate whether it has a relationship to and instance of the Storypak model. Since I expected Art instances to only related to one Storypak while Storypaks could have many associated artworks, I wrote the following custom field to only contain instances for which the value for “has_storypak” was
False.Next I added this form to an inline form for the Art model…
… and included the ArtInline in the ModelAdmin for Storypak. This gave me the drop-down containing the filtered list of model objects I was looking for. However I still have the problem mentioned above and this open question looking for a solution.