[Answered ]-How to Stop Django ModelForm From Creating Choices for a Foreign Key

2👍

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 = ....

Leave a comment