How to change ForeignKey display text in the Django Admin?
django, django-admin, foreign-keys, python, python-3.x
Solution
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)
Problem
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 its parent.