2011-08-19 29 views
5

我想在django的ORM中翻譯sql查詢。試圖使用annotate(),但我不設法得到相同的結果比sql查詢。如何使用django annotate()和aggregate()來分組查詢集?

這是我的模型:

class Fuel(models.Model): 
    type = models.CharField(max_length=150) 

class Station(models.Model): 
    name = models.CharField(max_length=150, null=True) 

class Price(models.Model): 
    fuel_type = models.ForeignKey(Fuel) 
    station = models.ForeignKey(Station) 
    price = models.FloatField() 
    date = models.DateTimeField('Date', auto_now_add=True) 

這是我嘗試在Django翻譯查詢:

select * from myapp_price where id IN ((select max(id) from myapp_price where station_id=121600 group by fuel_type_id)); 

這可能嗎?

回答

4

我得到預期的結果是這樣的:

q=Price.objects.filter(station=filters['station_id']).values('fuel_type').annotate(Max('id')).values('id__max') 
Price.objects.filter(pk__in=q) 
+0

非常感謝@orgoz,昨天我檢查你的答案,但我從第一次查詢跳過.values(「id__max」),這解決了我的問題:) –