Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#27496 closed Bug (duplicate)

Iterating over ModelChoiceField with RadioSelect widget duplicates query

Reported by: a-p-f Owned by: nobody
Component: Forms Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If you have a form with a ModelChoiceField using a RadioSelect widget and iterate over the individual radio inputs in your template (as demonstrated in the docs- https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#radioselect), then the field's queryset will be evaluated for each option. Actually, the query seems to be executed 2n + 5 times, where n is the number of objects returned by the queryset.

To reproduce this, use the following code with any model and watch your database server logs.

class BugTestForm(forms.Form):
    choice = forms.ModelChoiceField(queryset=MyModel.objects.all(), widget=forms.RadioSelect)

form = BugTestForm()
list(form['choice'])

The same issue occurs when using ModelMultipleChoiceField with a CheckboxSelectMultiple widget.

Change History (3)

comment:1 by Tim Graham, 8 years ago

Resolution: duplicate
Status: newclosed

Looks like a duplicate of #27002 which will be fixed in 1.11.

in reply to:  1 comment:2 by a-p-f, 8 years ago

Replying to Tim Graham:

Looks like a duplicate of #27002 which will be fixed in 1.11.

Actually, I believe this is a separate (but related) issue. That ticket indicates that the query is executed twice when rendering the widget normally. This issue is specific to iterating over the field, which causes the query to be executed 2n + 5 times.

I tried applying the patch which fixes #27002. Now the query is executed 2n times, instead of 2n + 5.

in reply to:  1 comment:3 by a-p-f, 8 years ago

Actually, this is a duplicate of #27001, which was fixed in 1.10.1. Just updated and the problem is gone.

Note: See TracTickets for help on using tickets.
Back to Top