开发者

How to use django annotate() and aggregate() to group a queryset?

开发者 https://www.devze.com 2023-03-29 02:51 出处:网络
I am trying to translate a sql query in django\'s ORM. Tried to use annotate() but I don\'t manage to get same results than the sql query.

I am trying to translate a sql query in django's ORM. Tried to use annotate() but I don't manage to get same results than the sql query.

This is my model :

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

class Station(models.Model):
    name = models.CharF开发者_如何转开发ield(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)

And this is the query I try to translate in django :

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

Is this possible ?


I get the expected results this way :

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号