4

Possible Duplicate:
Can “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?

I want to show some information on the admin list view of a model which comes from another, related model.

class Identity(models.Model):
  blocked = models.BooleanField()
  ...

class Person(models.Model):
  modelARef = OneToOneField("Identity", primary_key=True)
  descr     = models.CharField(max_length=255)
  name      = models.CharField(max_length=255)

The User should be able to add/edit "Person" on the admin page. As there ist no support for reverse inlining I have to show "Identity" on the admin page and then inline "Person". "Identity" only contains additional information to "Person" which should be visible on the admin page.

Now when I have a admin page for "Identity" how can I show fields from the "Person"-model on the list_display of "Identity"?

regards

EDIT: I can add some functions to "Identity" which query the related "Person" and return the needed value but if I do that there is no possibility to sort that column.

Community
  • 1
  • 1
Martin
  • 123
  • 2
  • 8

2 Answers2

13

You can use a list_display to add custom columns. I'd also advise updating the get_queryset() to make sure the related objects are only fetched on one query, instead of causing a query per row.

class IdentityAdmin(admin.ModelAdmin):
    list_display = ('blocked', 'person_name')

    def person_name(self, object):
        return object.person.name

    person_name.short_description = _("Person name")

    def get_queryset(self, request):
        # Prefetch related objects
        return super(IdentityAdmin, self).get_queryset(request).select_related('person')
vdboor
  • 21,914
  • 12
  • 83
  • 96
  • 1
    It seems that the function to update the queryset should be `get_queryset` instead of `queryset` per https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset – mikhuang Jan 06 '18 at 20:41
0

Not directly, but you can create a method that prints out what you want, and add the method name to list_display. See docs on list_display

jpic
  • 32,891
  • 5
  • 112
  • 113
  • Yes, I can create a method that prints out what I want but than the columns won't be sortable (as I wrote in my post) – Martin Sep 17 '12 at 08:57