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

前端 未结 3 406
独厮守ぢ
独厮守ぢ 2021-01-18 17:34

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

    class Category(m         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 17:57

    Define a method on the ModelAdmin class which returns the value of the related field, and include that in list_display.

    class ProductAdmin(admin.ModelAdmin):
        list_display = ('name', 'level')
        model = Product
    
        def level(self, obj):
            return obj.category.level
    

提交回复
热议问题