djangodropdownmodelchoicefield

Django limit records (options) for ModelChoiceField


I have a Model Reader with ModelChoiceField favourite_book which is a Foreign key. It is a DropDown menu and user can choose one from 40.000 possible options (records in the database). There is a problem when editing this Model object and this specific field because DropDown is being populated with all the records from the database which takes too much time and memory. So, I have to find a way to somehow render this field with a matching option (that user has previously selected and saved in DB) alone and not with thousands of other options. I tried:

readerForm.fields['books'].initial = Books.objects.get(id=url)

but initial doesn't work with bound forms.

I have $.ajax request that will later filter those 40.000 options based on input so user can choose some other option if needed.


Solution

  • After days of struggling with this, I finally came across this question which helped me solve this problem. BTW, I don't know why official documentation is missing regarding initializing forms, fields, instance, __init__() method etc - I think I've read around 50 Stackoverflow questions and didn't find in the official docs anything that was mentioned in those questions & answers. Anyhow, I defined __ init__ () method and modified ChoiceField as follows:

    class ReaderForm(forms.ModelForm):
    ...
    
    def __init__(self,*args,**kwargs):
        super(ReaderForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['favourite_book'].queryset = Book.objects.filter(id=self.instance.favourite_book.id)
    
    class Meta:
        model = Reader
        fields = "__all__"