How to display an attribute of a foreign key in the Django admin page

Viewed 5821

I want to display the level field of the category to which the product is related on the object's admin page.

    class Category(models.Model):
        name = models.CharField(max_length=50, default=False)
        level = models.IntegerField(help_text="1, 2 ,3 or 4")

    class Product(models.Model):
        category = models.ForeignKey(Category)
        name = models.CharField(max_length=100)


        prepopulated_fields = {'slug': ('name',)}
        fieldsets = [
            ('Product Info',{'fields': ['name', 'slug','partno','description']}),
            ('Categorisation',{'fields': ['brand','category']}),

I have found references to list_filter, but nothing regarding how to show the field.

Does anyone know how to do this?

4 Answers

To show the related field in a ModelAdmin's fieldset, the field must first be declared in readonly_fields.

  1. Define a method that returns the desired value.

  2. Include the method or its name in readonly_fields.

  3. Include the method or its name in its fieldset's "fields" list.

from django.contrib import admin
from .models import MyModel

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ['get_parent_name']  # Don't forget this!
    fieldsets = [('Parent info', {'fields': ['get_parent_name']} )]
    
    @admin.display(description='Parent')
    def get_parent_name(self, obj):
        return obj.parent.name

On the Change page, there will be a "Parent info" section with the object's parent's name.

Related