﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
25496	ModelChoiceField generates extra queries by not respecting prefetch_related	Matt d'Entremont	nobody	"''Note'': could be worked around if this were resolved: https://code.djangoproject.com/ticket/22841

When a `ModelChoiceField`'s choices are generated, the queryset's `prefetch_related` calls are not evaluated, which can lead to 1 query per choice if the model's `unicode` accesses a related field.

Example models:
{{{#!python
from django.db import models
class RelatedObj(models.Model):
    name = models.CharField(max_length=255)


class ObjWithRelated(models.Model):
    name = models.CharField(max_length=255)
    related = models.ManyToManyField(RelatedObj)

    def __unicode__(self):
        return '{}: {}'.format(self.name, self.related.count())

}}}

With many models,  we can see the following results:

{{{#!python
from django.db import connection
from django.forms import ModelChoiceField
from django.test.utils import CaptureQueriesContext


queryset = ObjWithRelated.objects.prefetch_related('related')
field = ModelChoiceField(queryset)

with CaptureQueriesContext(db.connection) as queries:
    list(field.choices)
print 'ModelChoiceField query count: {}'.format(len(queries))

with CaptureQueriesContext(db.connection) as queries:
    [str(obj) for obj in queryset]
print 'Regular query count: {}'.format(len(queries))
}}}

This will have the output of:

{{{#!comment
ModelChoiceField query count: <at least 1 query to evaluate the queryset + 1 extra query per ObjWithRelatedModel>
Regular query count: 2
}}}


There are ways to work around this, but ideally there would be a solution which wouldn't require a workaround. We're using [https://github.com/edoburu/django-parler django-parler] to translate models, without the prefetching we get 1 query per dropdown choice, per dropdown when a translated model is displayed in the django admin."	Bug	closed	Forms	1.8	Release blocker	fixed		marti@…	Ready for checkin	1	0	0	0	0	0
