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

查看:24
本文介绍了如何在 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屋!

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