Django等同于count和group by [英] Django equivalent for count and group by
本文介绍了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()方法,但是我看不到 可以适应那里。
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屋!
查看全文