5

djangoのORMでSQLクエリを翻訳しようとしています。annotate()を使用しようとしましたが、SQLクエリと同じ結果を得ることができません。

これは私のモデルです:

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

1 に答える 1

4

私はこの方法で期待される結果を得る:

q=Price.objects.filter(station=filters['station_id']).values('fuel_type').annotate(Max('id')).values('id__max')
Price.objects.filter(pk__in=q)
于 2011-08-21T17:37:08.637 に答える