Saturday, 13 September 2014

Django `CheckboxSelectMultiple` with `ModelMultipleChoiceField` generates too many queries (solution)

If you use django.forms.ModelMultipleChoiceField with the default widget (django.forms.widgets.SelectMultiple ), all's good.

However, if you need to generate checkboxes for your choices, and use django.forms.widgets.CheckboxSelectMultiple you'll notice that the field will generate alot of queries (one for each element in the queryset), which is really really bad. I personally ended up with hundred of queries.

Fix: add cache_choices=True to your django.forms.ModelMultipleChoiceField

Example:

Good practice:
test = forms.ModelMultipleChoiceField(
queryset=MyModel.objects.all(),
cache_choices=True,
widget=forms.CheckboxSelectMultiple)

Bad practice:
test = forms.ModelMultipleChoiceField(
queryset=MyModel.objects.all(),
widget=forms.CheckboxSelectMultiple)

django-logo-negative