在django管理员中,如果数据库中的字段为None或具有值,但我无法创建自定义选项,但我无法使其正常工作,则只能获取整个查询集,但无法获取数据ID这样我就可以过滤请求了。
有什么建议吗?
def formfield_for_choice_field(self, db_field, request, **kwargs):
ordered = False
qs = self.get_queryset(request)
for query in qs:
if query:
if query.order:
ordered = True
if db_field.name == "status":
if ordered:
kwargs['choices'] = (
('Ordered', 'Ordered'),
('Shipped', 'Shipped'),
('Delivered', 'Delivered'),
('Late', 'Late'),
('Never Arrived', 'Never Arrived'),
)
else:
kwargs['choices'] = (
('Shipped', 'Shipped'),
('Delivered', 'Delivered'),
('Late', 'Late'),
('Never Arrived', 'Never Arrived'),
)
return super(xxxxxx, self).formfield_for_choice_field(
db_field, request, **kwargs)
答案 0 :(得分:0)
由于在调用此函数时已经检索了模型实例,因此您可以将其挂接到该检索中并使模型实例在当前请求上下文中可用,因此您可以在有请求的任何地方轻松使用它:
def get_object(self, *args, **kwargs):
request._admin_obj = super(xxxxxx, self).get_object(*args, **kwargs)
return request._admin_obj
def formfield_for_choice_field(self, db_field, request, **kwargs):
if db_field.name == "status":
obj = request._admin_obj
if obj and obj.order:
kwargs['choices'] = # ordered_choices
else:
kwargs['choices'] = # unordered_choices
return super(xxxxxx, self).formfield_for_choice_field(
db_field, request, **kwargs)
另一种方法是在管理员中使用自定义ModelForm
并覆盖其__init__
来基于self.instance
修改字段的选择。