gpt4 book ai didi

python - 如何动态覆盖 Django Admin 中的 list_filter 字段?

转载 作者:行者123 更新时间:2023-12-01 06:27:08 25 4
gpt4 key购买 nike

我在 list_filter 中有几个字段。我必须创建一个为 list_filter 中的每个值调用的通用 model.SimpleListFilter

我无法为每个 list_filter 创建单独的类。

最好的解决方案是这样的:

class MyModelAdmin(MyCustomFilter):
list_filter = ('client_name', 'case_received_date')`

为每个 list_filter 字段调用 MyCustomFilter 中的 lookupsqueryset 方法。

# admin.py
class MyModelAdmin(admin.ModelAdmin):
list_display = ('client_name','client_application_number')
list_filter = ('client_name', 'case_received_date', MyCustomFilter)

class MyCustomFilter(admin.SimpleListFilter):
def lookups(self, request, model_admin):
pass

def queryset(self, request, queryset):
# Apply the filter selected, if any
pass

最佳答案

您可以使用函数生成无限数量的匿名类。以下是您的代码的更新:

class MyCustomFilter(admin.SimpleListFilter):
def lookups(self, request, model_admin):
pass

def queryset(self, request, queryset):
# Apply the filter selected, if any
pass

def my_custom_filter_maker(field):
class MyAnonymousCls(MyCustomFilter):
title = field
parameter_name = field

return MyAnonymousCls

class MyModelAdmin(admin.ModelAdmin):
list_display = ('client_name','client_application_number')
list_filter = ('client_name', 'case_received_date',
my_custom_filter_maker('field_name'), my_custom_filter_maker('another_field'))

关于python - 如何动态覆盖 Django Admin 中的 list_filter 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com