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)
开发者_如何学JAVA 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 only need to display it in list:
class Applicant(models.Model):
name = models.CharField(...)
email = models.CharField(...)
def __unicode__(self):
return "%s <%s>" % (self.name, self.email)
class ApplicationAdmin(model.ModelAdmin):
list_display = ['text', 'applicant']
Answer to your comment
but would like to have each field as a new line/row in the admin, not as a string.
Not sure if it is the best solution availabe but it will work:
class Application(models.Model):
@property
def applicant__name(self):
return self.applicant.name
# or maybe:
def __getattr__(self, name):
if name.startswith('applicant__'):
return gettattr(self.applicant,
name[len('applicant__'):])
raise AttributeError()
class ApplicationAdmin(model.ModelAdmin):
list_display = ['text', 'applicant__name']
精彩评论