2012-05-03 48 views
0

我正在嘗試通過相關對象的特徵來計算與條件和組相匹配的對象。舉例來說,如果我有這樣一組模型:已過濾的相關對象的聚合

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的查詢集聚集&註釋功能得到這樣的結果,我不認爲這是可能基於相關對象的領域聚集,但我想問,如果我錯過了什麼。

回答

0

如何:

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