开发者

Django - list_filter not working with methods

class MyUserAdmin(UserAdmin):
    list_display =  UserAdmin.list_display  + ('get_company',)
    list_filter = UserAdmin.list_filter + ('get_company',)
    inlines = [CompanyInline,]

    def get_company(self, obj):
        assignment = UserCompanyAssignment.objects.get(user__exact=obj.id)
        return assignment.company.name
    get_company.short_description = 'Company'

The list_filter doesn't work with for 'get_company'. It says

'MyUserAdmin.list_filter[3]' refers to field 'Company' that is missing from model 'User'.
开发者_运维百科

Any suggestions?


list_filter must point to model fields, not methods. You can point it to foreign keys, but for that to work in your case you must have changed the User model which I assume you haven't since you didn't post it.

I'm guessing the exception mesage refers to field 'Company' because you set short_description to 'Company'. Somewhat misleading, maybe a change in Django would be appropriate.

To do custom filtering, you can write your own FilterSpec, but it is not an official API yet.


list_display may contain methods, and if you want to do sorting on them, you can tell the admin to use a specific field by setting the admin_order_field attribute, like this:

def get_company(self, obj):
    # ...
get_company.admin_order_field = 'somefield'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜