2011-08-19 2 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) 

그리고 이것은 내가 장고에 번역하려고 쿼리입니다 :이게 가능

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, 당신의 대답을 확인 어제하지만 첫 번째 쿼리에서 ('id__max')를 .values를 생략, 이건 내 문제를 해결 :) –

관련 문제