Menu Close

How to filter ForeignKey choices in a Django ModelForm with Python?

Sometimes, we want to filter ForeignKey choices in a Django ModelForm with Python.

In this article, we’ll look at how to filter ForeignKey choices in a Django ModelForm with Python.

How to filter ForeignKey choices in a Django ModelForm with Python?

To filter ForeignKey choices in a Django ModelForm with Python, we can use the filter method.

For instance, we write

form.rate.queryset = Rate.objects.filter(company_id=the_company.id)

to set the values of the rates field to the queryset returned by

Rate.objects.filter(company_id=the_company.id)

Conclusion

To filter ForeignKey choices in a Django ModelForm with Python, we can use the filter method.

Posted in Python, Python Answers