Reputation: 1168
I want to create a foreign key relationship in a model, where it actually provides a select dropdown for the model form based on another field value of the model. Normally dropdown shows the values of __str__
methods return value. I want to keep this also since it used in other places.
For example, consider two models Order
and Item
.
Item
have fields called item_code
and item_name
.
__str__
will return item_name
.
Order
model will have foreign key to Item
model. But I want it provides the item_code
field values in the dropdown for item selection.
How can I achieve this without changing general foreign key behavior?
Upvotes: 0
Views: 487
Reputation: 599610
You would do this in the form, by defining a subclass of ModelChoiceField with a custom label_from_instance
method, as described in the documentation.
Upvotes: 1