使用filter,groupby,count()的Django查询

时间:2014-01-22 10:19:38

标签: python mysql django django-queryset

如何对以下mysql查询执行django查询:

This is Django model
class Passengers(models.Model):       
    id = models.CharField(max_length=128)        
    ref = models.CharField(max_length=128)
    orgId = models.ForeignKey(Organization)
    number = models.CharField(max_length=128)

MYSQL
------
SELECT `ref` , count( 'id' )
FROM `dispatcher_passengers`
WHERE `orgId_id` =1
GROUP BY `ref`

我有一个带有id,ref列的模型。

我想用'ref'获得计数(id)。

那么如何在django查询集格式中编写上述查询。

1 个答案:

答案 0 :(得分:0)

这样的方式:

refs = Passengers.objects.values('ref')
refs = set(refs)
ref_count = lambda ref: Passengers.objects.filter(ref = ref).count
counts = [ (ref, ref_count(ref)) for ref in refs ]

更新

from django.db.models import Count
count = Passengers.objects.values('ref').annotate(Count('id')).order_by()