简体   繁体   中英

foreign keys for specific primary key django forms

I have class Company, Driver and Car

class Company(models.Model):
title = models.CharField(max_length=256)
...

Class Car(models.Model):
...
company = ForeignKey('Company')    

class Driver(models.Model):
...
company = ForeignKey('Company')
company_car = OneToOneField('Car')

Also I have GenericView for Create and Update driver, and generic form.

I need form where when user select the company, company_car dropdown consist only Foreign Keys car objects for this company. I know about object_set feature and that`s trick possible with AJAX. But I have no idea how it realize

On your form field, you can specify a query set for the ModelChoiceField. You haven't given your form, but it could look something like this:

class MyForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.fields['car'] = ModelChoiceField(
          queryset = Car.objects.filter(company=company)
        )

Documentation is here: https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

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