Django - list_filter 不适用于方法

发布于 2024-10-04 23:52:51 字数 573 浏览 4 评论 0原文

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'

list_filter 不适用于“get_company”。它说

'MyUserAdmin.list_filter[3]' refers to field 'Company' that is missing from model 'User'.

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

家住魔仙堡 2024-10-11 23:52:52

list_filter 必须指向模型字段,而不是方法。您可以将其指向 外键< /a>,但要使其在您的情况下工作,您必须更改用户模型,我认为您没有更改,因为您没有发布它。

我猜测异常消息引用了“公司”字段,因为您将 short_description 设置为“公司”。有点误导,也许 Django 的改变是合适的。

要进行自定义过滤,您可以编写自己的FilterSpec,但它还不是官方API。


list_display 可能包含方法,如果您想对它们进行排序,您可以通过设置 admin_order_field 属性告诉管理员使用特定字段,如下所示:

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

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文