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 回答