#28296: Add support for aggregation through subqueries
-------------------------------------+-------------------------------------
     Reporter:  László Károlyi       |                    Owner:  nobody
         Type:  New feature          |                   Status:  new
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:  Accepted
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Sylvain Zimmer):

 Hello !

 I solved this with a custom class:

 {{{#!python

 class SubQueryCount(Subquery):
     output_field = models.IntegerField()
     def __init__(self, *args, **kwargs):
         Subquery.__init__(self, *args, **kwargs)
         self.queryset =
 self.queryset.annotate(cnt=Count("*")).values("cnt")
         self.queryset.query.set_group_by()  # values() adds a GROUP BY we
 don't want here

 subquery = Media.objects.filter(artist=OuterRef('id'))
 artists_with_count_medias =
 Artist.objects.all().annotate(count_medias=SubQueryCount(subquery))

 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/28296#comment:5>
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/065.6bc881c37f6cf8097043b262b623faac%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to