Menu Close

How to filter ForeignKey choices in a Python Django ModelForm?

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(

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


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

Posted in Python, Python Answers