Rob
Rob

Reputation: 2510

Showing fields from parent tables in Django Admin screens

I want to show a field in the admin screen from a model that is linked to from another model.

I have models like so:

class Location(models.Model):
    name = models.CharField(max_length = 128)
    description = models.TextField(blank = True)

class Building(models.Model):
    name = models.CharField(max_length = 128)
    description = models.TextField(blank = True)    
    location = models.ForeignKey(Location)  

class Room(models.Model):
    name = models.CharField(max_length = 128)
    description = models.TextField(blank = True)    
    building = models.ForeignKey(Building)

And admin models like this:

class BuildingAdmin(admin.ModelAdmin):
    list_display = ('name', 'location') 

class RoomAdmin(admin.ModelAdmin):
    list_display = ('name', 'building')

How can I show in the admin list for the Room model 3 columns, room name, building name and location name?

Thanks

Upvotes: 0

Views: 1693

Answers (1)

gruszczy
gruszczy

Reputation: 42198

You can write a custom method in admin and use it in list_display.

class PersonAdmin(admin.ModelAdmin):
    list_display = ('upper_case_name',)

    def upper_case_name(self, obj):
      return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

This way you can display whatever you want in list_display. Here you have full docs.

Upvotes: 1

Related Questions