Django 等价于 count 和 group by [英] Django equivalent for count and group by

查看:35
本文介绍了Django 等价于 count 和 group by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的模型:

I have a model that looks like this:

class Category(models.Model):
    name = models.CharField(max_length=60)

class Item(models.Model):
    name = models.CharField(max_length=60)
    category = models.ForeignKey(Category)

我想要为每个类别选择项目的计数(只是计数),所以在 SQL 中它会像这样简单:

I want select count (just the count) of items for each category, so in SQL it would be as simple as this:

select category_id, count(id) from item group by category_id

是否有类似的Django 方式"?还是纯 SQL 是唯一的选择?我熟悉 Django 中的 count( ) 方法,但是我不知道 group by 将如何适合那里.

Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the count( ) method in Django, however I don't see how group by would fit there.

推荐答案

这里,正如我刚刚发现的,是如何使用 Django 1.1 聚合 API 做到这一点:

Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:

from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))

这篇关于Django 等价于 count 和 group by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆