您还可以创建一个自定义 ModelChoiceField,您可以将函数传递给该字段。这样,如果您有不同的字段希望显示不同的属性,则只能有 1 个类:
class CustomModelChoiceField(forms.ModelChoiceField):
name_function = staticmethod(lambda obj: obj)
def __init__(self, name_function, *args, **kwargs):
if not name_function is None: self.name_function = name_function
super(CustomModelChoiceField, self).__init__(*args, **kwargs)
def label_from_instance(self, obj):
return self.name_function(obj);
然后,您可以像这样简单地调用它:
form_field = CustomModelChoiceField(
lambda obj: obj.get_full_name(),
queryset=Whatever.objects.all(),
)
如果你正在做一些动态的事情,你也可以传递 None ,它基本上默认为一个常规的 ModelChoiceField。我不是一个蟒蛇人,但这对我有用。