Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 694
Bryce Avatar asked Dec 18 '13 08:12

Bryce


People also ask

What is list_ display in Django?

It provides a simple UI for creating, editing and deleting data defined with the Django ORM. In this article we are going to enable the admin user interface for a simple model and customize it from a simple list view to a more user friendly table like interface.

What is Admin ModelAdmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

What is the purpose of the admin site in a Django project?

The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.


Video Answer


1 Answers

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

like image 182
yuvi Avatar answered Nov 07 '22 03:11

yuvi