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.
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']
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