Home >Backend Development >Python Tutorial >How to Filter ForeignKey Choices in Django ModelForms?
Django ModelForm Filtering ForeignKey Choices
Introduction
When creating forms in Django, it can be desirable to limit the choices presented to users for a specific field based on certain criteria. This can be particularly useful in scenarios involving hierarchical data, such as when selecting a foreign key.
Case Study: Selecting ForeignKey Choices in a ModelForm
Let's consider a hypothetical Django project with the following models:
class Company(models.Model): name = ... class Rate(models.Model): company = models.ForeignKey(Company) name = ... class Client(models.Model): name = ... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate)
In this case, each company has multiple rates and clients. Each client must have a base rate chosen from its parent company's rates, not another company's rates.
Limiting ForeignKey Choices Using QuerySet Filtering
To limit the choices for the Rate field in the Client form to only those rates associated with the selected company, we can modify our ClientForm class as follows:
class ClientForm(ModelForm): class Meta: model = Client fields = ['name', 'base_rate'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['base_rate'].queryset = Rate.objects.filter(company_id=self.instance.company_id)
In this code, we retrieve the Company ID from the instance associated with the form. This ensures that the Rate choices are filtered based on the correct company.
Additional Notes
The above is the detailed content of How to Filter ForeignKey Choices in Django ModelForms?. For more information, please follow other related articles on the PHP Chinese website!