Chuck
Chuck

Reputation: 1089

How to Stop Django ModelForm From Creating Choices for a Foreign Key

I have a Django model with a Foreign key to a table that contains about 50,000 records. I am using the Django forms.ModelForm to create a form. The problem is I only need a small subset of the records from the table the Foreign key points to.

I am able to create that subset of choices in the init method. How can I prevent ModelForm from creating that initial set of choices?

I tried using the widgets parameter in the Meta method. But Django debug toolbar indicates the database is still being hit.

Thanks

Upvotes: 1

Views: 553

Answers (1)

The autogenerated ModelChoiceField will have its queryset initialized to the default. The widget is not where you are supposed to customize the queryset property.

Define the ModelChoiceField manually, initialize its queryset to be empty. Remember to name the ModelChoiceField the same as the one that would have been automatically generated, and remember to mention that field in the fields tuple. Now you can set the queryset from the constructor and avoid the database being hit twice.

If you are lucky (and you probably are, please test though), the queryset has not been evaluated during construction, and in that case, defining the ModelChoiceField manually is not required.

class YourModelForm(ModelForm):
    your_fk_field_name = forms.ModelChoiceField(queryset=YourModel.objects.none())

    class Meta:
        model = YourModel
        fields = ('your_fk_field_name', .......)

    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['your_fk_field_name'].queryset = ....

Upvotes: 2

Related Questions