Django admin自定义函数报错,TypeError: post_count() missing 1 required positional argument: 'obj'

在学习开发django的时候,碰到了这个问题,源码:

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    def post_count(self, obj):
        return obj.post_set.count()

    post_count.short_description = '文章数量'

    list_display = ('name', 'status', 'is_nav', 'created_time', post_count)
    fields = ('name', 'status', 'is_nav')

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(CategoryAdmin, self).save_model(request, obj, form, change)

然后报错从字面意思看是少了一个参数,django的自定义函数就是这样子的啊,后面发现在

list_display = ('name', 'status', 'is_nav', 'created_time', post_count)中,我写的post_count是属性不是字符,而其他的参数都是字符串,就好奇把这个改了下,结果就成功了.

list_display = ('name', 'status', 'is_nav', 'created_time', 'post_count')

后面去搜索.大概的意思是这里django用了反射,从字符串去找到相应的属性或方法,原来反射是在这里用的,大开眼界.

你可能感兴趣的:(django)