答案 0 :(得分:2)
您可以使用ModelChoiceField
。这是外键的默认表单字段。
class MyForm(forms.formForm):
my_field = forms.ModelChoiceField(queryset=MyModel.objects.all())
默认情况下,option
的值将是主键,标签将由__str__
方法给出。但你可以覆盖这个:
class MyForm(forms.formForm):
my_field = forms.ModelChoiceField(queryset=MyModel.objects.all(),
to_field_name='foo')
# Where foo is a field of `MyModel`.
class MyCustomModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return '{} ({})'.format(obj.foo, obj.bar)
class MyForm(forms.formForm):
my_field = MyCustomModelChoiceField(queryset=MyModel.objects.all())