Access from django admin list_display, a value from a One-To-One table

独自空忆成欢 提交于 2019-12-04 19:16:22

问题


Given a one-to-one extension a model, such as the Django User model:

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")

How can I display that in the admin?

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

A near match question is Django Admin: How to display value of fields with list_display from two models which are in oneToOne relation?


回答1:


The general method would be:

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

x here is the object of the model you are displaying



来源:https://stackoverflow.com/questions/20652949/access-from-django-admin-list-display-a-value-from-a-one-to-one-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!