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


Good practice:

Bad practice: