Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ForeignKey display text in the Django Admin?

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.

like image 694
robos85 Avatar asked Jul 26 '11 21:07

robos85


People also ask

What is Admin ModelAdmin in Django?

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.

What is Django ForeignKey model?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.


1 Answers

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) 
like image 135
Botond Béres Avatar answered Oct 07 '22 18:10

Botond Béres