How can I change the display text in a <select> field while selecting a field which is a ForeignKey?
I need to display not only the name of ForeignKey, but also the name of it's parent.
One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.
If you want it to take effect only in admin, and not globally, then you could create a custom ModelChoiceField subclass, use that in a custom ModelForm and then set the relevant admin class to use your customized form. Using an example which has a ForeignKey to the Person model used by @Enrique:
class Invoice(models.Model): person = models.ForeignKey(Person) .... class InvoiceAdmin(admin.ModelAdmin): form = MyInvoiceAdminForm class MyInvoiceAdminForm(forms.ModelForm): person = CustomModelChoiceField(queryset=Person.objects.all()) class Meta: model = Invoice class CustomModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s %s" % (obj.first_name, obj.last_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With