如何在django管理页面中显示外键的属性 [英] how to display an attribute of a foreign key in django admin page

查看:2994
本文介绍了如何在django管理页面中显示外键的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对象的管理页面中,我想显示产品所属类别的级别。从下面的显示中切出了不重要的领域。

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

类产品(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length = 100)


prepopulated_fields = {'slug':('name',)}
fieldsets = [
('产品信息',{'fields':['name','slug','partno','description']}),
('Categorization',{'fields' ,'category']}),

显然我已经尝试了一些工作和谷歌很多,但我已经找到引用list_filter批次,但没有什么关于只显示该字段。
最好的猜测是

 'category__level'
解决方案

定义一个方法在返回相关字段的值的ModelAdmin类中,并将其包含在 list_display 中。

 code> class ProductAdmin(admin.ModelAdmin):
list_display =('name','level')
model = Product

def level(self,obj ):
return obj.category.level


I want to display the level of the category that the product belongs to, in the admin page for the object. snipped a lot fo the unimportant fields out of the display below.

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']}),

obviously i've tried a little to get this working and googled a lot, but i've found reference to list_filter lots, but nothing about just showing the field. best guess was

'category__level'

anyone know the right way to do this?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆