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

Comments

Popular posts from this blog

Improve font rendering for IntelliJ IDEA / Pycharm in Ubuntu

Fix - Updated from OSX El Capitan Gold Master to Final Release, andbeta update keeps showing in AppStore