Django——记一次 admin.E108错误

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37049781/article/details/82851180

在一次admin注册中遇见了以下错误:

<class 'demo.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'company__name', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'daquan.Product'.
<class 'demo.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'category__name', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'daquan.Product'.

admin 代码为:

from demo.contrib import admin
from demo.models import Product

class ProductAdmin(admin.ModelAdmin):
    list_display = ('company__name', 'category__name', 'product_name', 'sale_status', 'literal_code')

admin.site.register(Product, ProductAdmin)

这样写并没有出现预期的效果,而是直接报了上面的错误。

解决方法:

class ProductAdmin(admin.ModelAdmin):
    list_display = ('get_company', 'get_category', 'product_name', 'sale_status', 'literal_code')
    #搜索域支持双下划线关联
    #search_fields =(company__name, category__name)

    def get_company(self, obj):
        return obj.company.name

    def get_category(self, obj):
        return obj.category.name
        
	#get_company.admin_order_field  = '所属公司'  #准许排序
    get_company.short_description = '所属公司'  #修改表头字段名

也可以将两个get函数写在该models模型下。

猜你喜欢

转载自blog.csdn.net/qq_37049781/article/details/82851180