是否有任何管理模型方法,如 get_list_display() 或某种方式,我可以有一些条件来设置不同的 list_display 值?
class FooAdmin (model.ModelAdmin):
# ...
def get_list_display ():
if some_cond:
return ('field', 'tuple',)
return ('other', 'field', 'tuple',)
最佳答案
ModelAdmin
类有一个名为 get_list_display
的方法,该方法将 request 作为参数,默认返回该类的 list_display
属性。
所以你可以这样做:
class ShowEFilter(SimpleListFilter):
""" A dummy filter which just adds a filter option to show the E column,
but doesn't modify the queryset.
"""
title = _("Show E column")
parameter_name = "show_e"
def lookups(self, request, model_admin):
return [
("yes", "Yes"),
]
def queryset(self, request, queryset):
return queryset
class SomeModelAdmin(admin.ModelAdmin):
list_display = (
"a",
"b",
"c",
"d",
"e"
)
list_filter = (
ShowEFilter,
)
def get_list_display(self, request):
""" Removes the E column unless "Yes" has been selected in the
dummy filter.
"""
list_display = list(self.list_display)
if request.GET.get("show_e", "no") != "yes":
list_display.remove("e")
return list_display
关于Django 管理员 : Setting list_display conditionally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377520/