【问题标题】:Access from django admin list_display, a value from a One-To-One table从 django admin list_display 访问,来自一对一表的值
【发布时间】:2014-01-06 07:47:28
【问题描述】:

给定一个模型的一对一扩展,例如 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?

【问题讨论】:

    标签: django django-admin django-1.5


    【解决方案1】:

    一般的方法是:

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

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

    【讨论】:

    • 如果您希望它是可编辑的列表怎么办?
    猜你喜欢
    • 2016-01-05
    • 2017-08-25
    • 1970-01-01
    • 2019-07-28
    • 2019-09-17
    • 2013-03-07
    • 2013-04-28
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多