我相信问题的答案很简单,但是我找不到任何地方。这是我的困境。我有两个模型:Member和MemberDetail,它们处于oneToOne关系中,如下所示:

class Member(models.Model):
   ID = models.AutoField(primary_key=True)
   FIRST_NAME = models.CharField('First name', max_length=50)
   LAST_NAME = models.CharField('Last name', max_length=50)
   def __unicode__(self):
      return u'%s %s' % (self.FIRST_NAME, self.LAST_NAME)

class MemberDetail(models.Model):
   member = models.OneToOneField(Member, primary_key=True)
   DATE_OF_BIRTH = models.DateField('Date of birth')
   EMAIL = models.EmailField('E-mail')
   PHONE = models.CharField('Phone', max_length=15)

现在,在我的admin.py中,我想为成员显示表及其所有数据,如下所示:
class MemberDetailInline(admin.TabularInline):
    model = MemberDetail

class MemberAdmin(admin.ModelAdmin):
    list_display = ("FIRST_NAME", "LAST_NAME", "date_of_birth", "email", "phone")
    inlines = [
        MemberDetailInline,
    ]

admin.site.register(Member, MemberAdmin)

我根本不知道如何写list_display的“date_of_birth”,“email”和“phone”部分。我能做的最接近的事情是在内联之后添加以下内容:
def date_of_birth(self, MemberDetail):
    return MemberDetail.DATE_OF_BIRTH
def date_of_birth(self, MemberDetail):
    return MemberDetail.EMAIL
def date_of_birth(self, MemberDetail):
    return MemberDetail.PHONE

但字段在页面上显示为空。解决办法是什么?谢谢。

最佳答案

最后!!!我解决了我认为这很简单,但是我不得不以其他方式并通过多表继承来做到这一点:

models.py
class Member(models.Model):
    ID = models.AutoField(primary_key=True)
    FIRST_NAME = models.CharField('First name', max_length=50)
    LAST_NAME = models.CharField('Last name', max_length=50)

# Using multi table inheritance - automaticly creates one to one field
class MemberDetail(Member):
    DATE_OF_BIRTH = models.DateField('Date of birth')
    EMAIL = models.EmailField('E-mail')
    PHONE = models.CharField('Phone', max_length=15)

现在用于admin.py
admin.py
class MemberDetailAdmin(admin.ModelAdmin):
    list_display = ("FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "EMAIL", "PHONE")

admin.site.register(MemberDetail, MemberDetailAdmin)

就是这样。也许还有其他解决方案,但这对我有好处。

关于Django管理员: How to display value of fields with list_display from two models which are in oneToOne relation?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14328714/

10-10 23:50