mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
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.
This commit is contained in:
committed by
Anssi Kääriäinen
parent
4202d9cf0c
commit
539e3693d4
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user