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

1

10

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?

Actualize answered 18/12, 2013 at 8:22 Comment(0)
K
24

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

Khmer answered 18/12, 2013 at 8:32 Comment(1)
What if you wanted it to be list editable?Outermost

© 2022 - 2024 — McMap. All rights reserved.