#25496: ModelChoiceField generates extra queries by not respecting 
prefetch_related
-------------------------------+--------------------------------------
     Reporter:  mdentremont    |                    Owner:  nobody
         Type:  Uncategorized  |                   Status:  closed
    Component:  Forms          |                  Version:
     Severity:  Normal         |               Resolution:  invalid
     Keywords:                 |             Triage Stage:  Unreviewed
    Has patch:  0              |      Needs documentation:  0
  Needs tests:  0              |  Patch needs improvement:  0
Easy pickings:  0              |                    UI/UX:  0
-------------------------------+--------------------------------------
Changes (by charettes):

 * status:  new => closed
 * needs_better_patch:   => 0
 * resolution:   => invalid
 * needs_tests:   => 0
 * needs_docs:   => 0


Comment:

 Hi mdentremont,

 I think you misunderstood how `prefetch_related` and `count()` interact.
 The `count()` method never takes prefetched data into consideration and
 always result in a new query.

 If you want to avoid an extra query I suggest you `annotate()` your
 queryset with its count of related objects and adapt your models
 `__unicode__` to lookup the annotated attribute first and fallback to
 calling `self.related.count()`:

 {{{#!python
 from django.db import models

 class RelatedObj(models.Model):
     name = models.CharField(max_length=255)

 class ObjWithRelated(models.Model):
     related = models.ManyToManyField(RelatedObj)

     def __unicode__(self):
         related_count = getattr(self, 'related_count', None)
         if related_count is None:
             related_count = self.related.count()
         return '{}: {}'.format(self.name, related_count)

 queryset =
 ObjWithRelated.objects.annotate(related_count=models.Count('related'))
 field = ModelChoiceField(queryset)
 }}}

 Please use support channels before filling a ticket
 wiki:TicketClosingReasons/UseSupportChannels

--
Ticket URL: <https://code.djangoproject.com/ticket/25496#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/069.49c889a5cf444751821cac37dac0c2f3%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to