#26010: I need to count objects in a queryset by year and month
-------------------------------------+-------------------------------------
     Reporter:  mahmoodkhan          |                    Owner:  nobody
         Type:  New feature          |                   Status:  closed
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  invalid
     Keywords:  Queryset.extra       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by mahmoodkhan):

 Thanks! much appreciated.

 Replying to [comment:1 charettes]:
 > Hi mahmoodkhan,
 >
 > You don't `extra()` to achieve this. There's already a couple of open
 tickets that you can relate to (#25774 comes to mind) but you should
 annotate your queryset with a
 [https://docs.djangoproject.com/en/1.9/ref/models/lookups/#transform-
 reference Transform] in order to extract the year and months.
 >
 > If you don't want to write your own Transform subclass you can use the
 undocumented `MonthTransform` and `YearTransform` to annotate your
 queryset:
 >
 > {{{#!python
 > from django.db.models.lookups import MonthTransform as Month,
 YearTransform as Year
 >
 > Item.objects.annotate(
 >     year=Year('date'),
 >     month=Month('date'),
 > ).values('year', 'month').annotate(count=Count('pk'))
 > }}}
 >
 > Keep in mind that you're relying on a private API (used internally to
 implement the `__month` and `__year` lookups) that might be moved around
 or replaced.
 >
 > Once `values()` allows transforms and lookups you should be able to
 simply do this:
 >
 > {{{#!python
 > Item.objects.values('date__year',
 'date__month').annotate(count=Count('pk'))
 > }}}

--
Ticket URL: <https://code.djangoproject.com/ticket/26010#comment:2>
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.9d1a8450c71ed4cdbff1c7bb426fe30d%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to