On Wed, Jun 8, 2011 at 10:11 AM, Thomas Weholt <[email protected]>wrote:

> Say I got a model like so:
>
> class Article(models.Model):
>    title = models.CharField(max_length=100)
>    text = models.TextField()
>    category = models.CharField(max_length=20)
>    author = models.CharField(max_length=50)
>
> Article.objects.create(title="Foo", text="Story about foo",
> category="adventure", author="jane")
> Article.objects.create(title="Bar", text="Story about bar",
> category="adventure", author="joe")
> Article.objects.create(title="Cheese", text="Story about cheese",
> category="adventure", author="joe")
> Article.objects.create(title="Perl", text="Story about perl",
> category="horror", author="jane")
> Article.objects.create(title="Java", text="Story about java",
> category="horror", author="joe")
> Article.objects.create(title="Pizza", text="Story about pizza",
> category="cooking", author="joe")
>
> I've tried to use aggregation to find how many articles written by joe
> there are of each category, but so far I'm not getting anywhere.
>
> Desired output:
>
> [
>    {'category': 'adventure', 'count': 2},
>    {'category': 'horror', 'count': 1},
>    {'category': 'cooking', 'count': 1}
> ]
>
> I just cant get my head wrapped around the orm aggregation, in this is
> easy using raw SQL, but I don't want to.
>

Is this not something like:

Article.objects.values('category').annotate(count=models.Count('id'))

? The idea being that you group the objects by category, and then count the
number of distinct ids within each category.

The docs mention that the default ordering can get in the way of this
sometimes, so you probably want to clear it first, like this:

Article.objects.values('category').annotate(count=models.Count('id')).order_by()

That should get you all of the data for your desired output -- it might not
be an actual list of actual dicts, but it should be structured in the same
way.

-- 
Regards,
Ian Clelland
<[email protected]>

-- 
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.

Reply via email to