关于django:显示childs admin(list_display)中的父字段

Display parent fields in childs admin (list_display)

这是一小段models.py

1
2
3
4
5
6
7
class Applicant(models.Model):
    name = models.CharField(...)
    email = models.CharField(...)

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

这是我的admin.py:

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

admin.site.register(Application, ApplicationAdmin)

在applicationadmin中,我要显示申请人的姓名和电子邮件。

你问之前试过什么?我看过以下代码,但它不起作用:

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

我看过modeladmin.inlines,但正如我们所看到的,父/子关系必须颠倒。

有什么建议吗?如何在"应用程序管理"中显示申请人姓名/电子邮件。不必迁移带有新字段等的数据库。


你可以像列表显示文档中的第四种可能性那样做。只需向应用程序模型添加一个方法,如下所示:

1
2
3
4
5
6
7
8
9
10
11
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'

然后您可以像这样设置ModelAdmin:

1
2
class ApplicationAdmin(model.ModelAdmin):
    list_display = ['text', 'applicant_name', 'applicant_email']


如果只需要在列表中显示:

1
2
3
4
5
6
7
8
9
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']

回答你的意见

but would like to have each field as a new line/row in the admin, not as a string.

不确定它是否是可用的最佳解决方案,但它将起作用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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']