Categories
Python Answers

How to filter ForeignKey choices in a Python Django ModelForm?

Spread the love

To filter ForeignKey choices in a Python Django ModelForm, we set the quertset property to the queryset with the filtered data.

For instance, we write

class ClientAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientAdminForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)

class ClientAdmin(admin.ModelAdmin):
    form = ClientAdminForm

to add the ClientAdminForm that sets the base_rate field’s queryset to the filtered Rate query set with

Rate.objects.filter(company=self.instance.company)

Then we add the ClientAdminForm form as the form to use in the ClientAdmin section of Django admin.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *