如何在Django管理页面中显示外键的属性 [英] How to display an attribute of a foreign key in the Django admin page
本文介绍了如何在Django管理页面中显示外键的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在对象的管理页面上显示与product
相关的category
的级别字段.
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']}),
我找到了对list_filter的引用,但是关于如何显示该字段却一无所获.
I have found references to list_filter, but nothing regarding how to show the field.
有人知道该怎么做吗?
推荐答案
在ModelAdmin类上定义一个方法,该方法返回相关字段的值,并将其包含在list_display
中.
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
这篇关于如何在Django管理页面中显示外键的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文