简体   繁体   中英

Django Exclude ForeignKey field from ModelChoiceField

I have two models:

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)

now on my forms.py:

class MyForm(forms.Form):
    drivers = Driver.objects.order_by('name')
    drivers_list = forms.ModelChoiceField(drivers, empty_label='* Driver *', label='Driver')

The problem is drivers_list also includes the vehicles in the list. How can I prevent this form from including the ForeignKey field into the ModelChoiceField?

Why are you not using model form for drivers,

class DriverForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['name', 'vehicle']

For your own forms,

class MyForm(forms.Form):
    driver_list = forms.ModelChoiceField(queryset=Driver.objects.order_by('name'))
    # then other attributes which you want to map with driver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM