从django admin list_display访问,这是One-To-One表中的值

时间:2013-12-18 08:22:35

标签: django django-admin django-1.5

给定一个模型的一对一扩展,例如Django User模型:

class UserProfile(models.Model):
     user        = models.OneToOneField(User, related_name='profile', unique=True)
     avatar      = models.ImageField(_('Avatar'))
     foo         = models.CharField(max_length=100, verbose_name="xxx")

如何在管理员中显示该内容?

class UserAdmin(admin.ModelAdmin):
     list_display = ('email', 'profile__foo' <--NOT WORKING )

近似匹配问题是Django Admin: How to display value of fields with list_display from two models which are in oneToOne relation?

1 个答案:

答案 0 :(得分:11)

一般方法是:

class UseAdmin(admin.ModelAdmin):
    list_display = ('email', 'profile_foo')
    def profile_foo(self, x):
        return x.profile.foo
    profile_foo.short_description = 'foo'

x这是您正在显示的模型的对象