我有两种模式:
class Vehicle(Model):
name = models.CharField(max_length=50)
class Driver(Model):
vehicle = models.ForeignKey(Vehicle, related_name='owned_vehicle')
name = models.CharField(max_length=100)
现在在我的forms.py上:
class MyForm(forms.Form):
drivers = Driver.objects.order_by('name')
drivers_list = forms.ModelChoiceField(drivers, empty_label='* Driver *', label='Driver')
问题是drivers_list
还包括列表中的vehicles
。
如何防止此表单将ForeignKey字段包含在ModelChoiceField中?
答案 0 :(得分:1)
为什么不使用驱动程序的模型表单,
class DriverForm(forms.ModelForm):
class Meta:
model = Article
fields = ['name', 'vehicle']
对于您自己的表单,
class MyForm(forms.Form):
driver_list = forms.ModelChoiceField(queryset=Driver.objects.order_by('name'))
# then other attributes which you want to map with driver