Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display parent fields in childs admin (list_display)

Here is a snippet of models.py

class Applicant(models.Model):
    name = models.CharField(...)
    email = models.CharField(...)

class Application(models.Model):
    applicant = models.ForeignKey(Applicant)
    text = models.TextField(...)

Here is my admin.py:

class ApplicationAdmin(model.ModelAdmin):
    list_display = ['text', *******]

admin.site.register(Application, ApplicationAdmin)

In the ApplicationAdmin I want to present the Applicants name and email.

What have you tried before asking SO?
I have looked at the following code, which does not work:

list_display = ['text', 'applicant__name','applicant__email']

I have looked at ModelAdmin.inlines but as one can see, the parent/child relationship have to be reversed.

Any suggestions? How can I display an applicants name/email in Applications admin. Prefferably without migrating the database with new fields etc.

like image 483
hermansc Avatar asked Feb 01 '11 21:02

hermansc


1 Answers

You can do it like the fourth possibility in the list_display docs. Just add a method to your Application model like so:

class Application(models.Model):
    applicant = models.ForeignKey(Applicant)
    text = models.TextField(...)

    def applicant_name(self):
        return self.applicant.name
    applicant_name.short_description = 'Applicant Name'

    def applicant_email(self):
        return self.applicant.email
    applicant_email.short_description = 'Applicant Email'

And then you can setup your ModelAdmin like so:

class ApplicationAdmin(model.ModelAdmin):
    list_display = ['text', 'applicant_name', 'applicant_email']
like image 111
meshantz Avatar answered Nov 07 '22 07:11

meshantz