是否有任何管理模型方法,如get_list_display()或某种方式我可以设置一些条件来设置不同的list_display值?
class FooAdmin (model.ModelAdmin):
# ...
def get_list_display ():
if some_cond:
return ('field', 'tuple',)
return ('other', 'field', 'tuple',)
答案 0 :(得分:0)
你有没有尝试过制作这个属性?
class FooAdmin(admin.ModelAdmin):
@property
def list_display(self):
if some_cond:
return ('field','tuple')
return ('other','field','tuple')
我没有,但它可能有用。
我也很确定你可以拼写它:
class FooAdmin(admin.ModelAdmin):
if CONDITION:
list_display = ('field','tuple')
else:
list_display = ('other','field','tuple')
但是这个只会在解释FooAdmin类时运行检查:但是如果你将测试基于settings.SOME_VALUE,那么它可能会起作用。
另请注意,第一个示例中的self
是FooAdmin类的实例,而不是Foo本身。
答案 1 :(得分:0)
您想要覆盖admin.ModelAdmin类的changelist_view方法:
def changelist_view(self, request, extra_context=None):
# just in case you are having problems with carry over from previous
# iterations of the view, always SET the self.list_display instead of adding
# to it
if something:
self.list_display = ['action_checkbox'] + ['dynamic_field_1']
else:
self.list_display = ['action_checkbox'] + ['dynamic_field_2']
return super(MyModelAdminClass, self).changelist_view(request, extra_context)
'action_checkbox'是django用来知道在左侧显示操作下拉列表的复选框,因此请确保将其包含在设置self.list_display中。像往常一样,如果您只是为ModelAdmin类设置list_display,通常不需要包含它。
答案 2 :(得分:0)
ModelAdmin
类具有一个名为get_list_display
的方法,该方法将请求作为参数,默认情况下返回该类的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