[1.10.x] Fixed #27001 -- Fixed a query count regression in ModelChoiceField with RadioSelect.

Backport of c5ebfda002 from master
This commit is contained in:
Alex Hill 2016-08-03 11:12:06 +08:00 committed by Tim Graham
parent a8b8ef114d
commit 86ae2b22ae
3 changed files with 16 additions and 2 deletions

View File

@ -693,8 +693,11 @@ class ChoiceFieldRenderer(object):
self.choices = choices self.choices = choices
def __getitem__(self, idx): def __getitem__(self, idx):
choice = list(self.choices)[idx] # Let the IndexError propagate return list(self)[idx]
return self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, idx)
def __iter__(self):
for idx, choice in enumerate(self.choices):
yield self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, idx)
def __str__(self): def __str__(self):
return self.render() return self.render()

View File

@ -20,3 +20,6 @@ Bugfixes
* Fixed a checks framework crash with an empty ``Meta.default_permissions`` * Fixed a checks framework crash with an empty ``Meta.default_permissions``
(:ticket:`26997`). (:ticket:`26997`).
* Fixed a regression in the number of queries when using ``RadioSelect`` with a
``ModelChoiceField`` form field (:ticket:`27001`).

View File

@ -1539,6 +1539,14 @@ class ModelChoiceFieldTests(TestCase):
self.assertEqual(form.errors, {}) self.assertEqual(form.errors, {})
self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk]) self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk])
def test_radioselect_num_queries(self):
class CategoriesForm(forms.Form):
categories = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)
template = Template('{% for widget in form.categories %}{{ widget }}{% endfor %}')
with self.assertNumQueries(2):
template.render(Context({'form': CategoriesForm()}))
class ModelMultipleChoiceFieldTests(TestCase): class ModelMultipleChoiceFieldTests(TestCase):
def setUp(self): def setUp(self):