已过滤的相关对象的聚合

时间:2012-05-03 21:44:54

标签: django django-queryset

我试图通过相关对象的特征来计算与标准和组匹配的对象。例如,如果我有一组这样的模型:

class Office(User):
    name = models.CharField(max_length=50)
    city = models.CharField(max_length=50)

class Staff(User):
    home_office = models.ForeignKey(Office)

class Appointment(models.Model):
    appt_start = models.DateTimeField()
    appt_end = models.DateTimeField()
    client = models.ForeignKey(User)
    provider = models.ForeignKey(Staff)
    result = models.CharField(max_length=50)

我希望获得导致成功的约会数量"对于每个办公室,我可以像这样执行一个原始SQL查询:

SELECT office.name, COUNT(appointment.id)
    FROM appointment
        JOIN staff ON staff.id = appointment.provider_id
        JOIN office ON office.id = staff.home_office_id
    WHERE appointment.result = 'success' GROUP BY office.name;

我更喜欢使用ORM和Django的QuerySet聚合&获取此结果。注释功能如果可能,但在阅读文档之后我并不认为可以根据相关对象的字段进行聚合,但我想问一下我是否错过了某些内容。

1 个答案:

答案 0 :(得分:0)

这个怎么样:

Office.objects.filter(
    staff__appointment__result='success'
).values('name').annotate(appointments=models.Count('staff__appointment'))