From 539e3693d4712b249a95cfad8cfdeecdad1777a6 Mon Sep 17 00:00:00 2001 From: Jim Bailey Date: Fri, 1 Nov 2013 12:55:35 +0000 Subject: Fixed #20849 -- ModelForms do not work well with prefetch_related. model_to_dict() (used when rendering forms) queries the database to get the list of primary keys for ManyToMany fields. This is unnecessary if the field queryset has been prefetched, all the keys are already in memory and can be obtained with a simple iteration. --- django/forms/models.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'django/forms') diff --git a/django/forms/models.py b/django/forms/models.py index 71da43390c..32f0f043ae 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -134,7 +134,11 @@ def model_to_dict(instance, fields=None, exclude=None): data[f.name] = [] else: # MultipleChoiceWidget needs a list of pks, not object instances. - data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True)) + qs = f.value_from_object(instance) + if qs._result_cache is not None: + data[f.name] = [item.pk for item in qs] + else: + data[f.name] = list(qs.values_list('pk', flat=True)) else: data[f.name] = f.value_from_object(instance) return data -- cgit v1.3