On 18 Feb, 19:08, Jacob Kaplan-Moss <[email protected]>
wrote:
> On Wed, Feb 18, 2009 at 11:12 AM, Deniz Dogan <[email protected]>
> wrote:
> > Let's say I have a model called Bike with a DateField called
> > "production_date". Now I want to get all of the Bikes and group them
> > by their production date. How would I do this in Django? I can't seem
> > to figure it out.
>
> For this type of query, you need to ask yourself two things:
>
> The first question is easy: What kind of aggregate do I want? You want
> a count, so you'd use the ``Count()`` aggregate (i.e.
> ``django.db.models.Count``). That's simple; I'll bet you already
> figured that part out.
>
> The second part is more tricky: what is the set of fields I'm grouping
> over? By default, it's all the fields on the model, so a simple
> ``aggregate(Count(production_date))`` basically is the same as a
> ``COUNT(*)``, which you don't want::
>
> >>> Bike.objects.aggregate(Count('production_date'))
> {'production_date__count': 7}
>
> So you need to change the list of fields you're grouping over. You do
> this by using ``values()``; the important part of the docs to read
> ishttp://docs.djangoproject.com/en/dev/topics/db/aggregation/#values;
> make sure to pay attention to the part about the order of
> ``annotate()`` and ``values()``.
>
> If you read that carefully, you'll see that to change the set of
> grouped fields you'll want to call ``values()`` before calling
> ``annotate()``::
>
> >>> qs = Bike.objects.values('production_date') \
> ... .annotate(count=Count('production_date')) \
> >>> for r in qs:
> ... print "%(production_date)s: %(count)s bikes" % r
> 2008-01-01 2 bikes
> 2008-01-02 1 bikes
> 2008-01-03 1 bikes
> 2008-01-04 2 bikes
> 2008-01-05 1 bikes
>
> Hope that helps!
>
> Jacob
Thanks for your response, Jacob!
However, one of us has misunderstood something here, and I'm not sure
whether that's you or me. With your method I get the amount of bikes
that were made on each day, but what I want is to have is a structure
similar to this one:
{ 'production_date' : 2008-01-02,
'bikes' : [Bike 1, Bike 2],
'production_date' : 2008-02-09,
'bikes : [Bike 7, Bike 4]
}
I.e. I want to be able to access the actual Bike objects, not how many
that were made on each day.
Thanks again,
Deniz
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---