Python 在django中选择具有单个group by的多个字段
我使用Django查询作为:Python 在django中选择具有单个group by的多个字段,python,django,django-templates,Python,Django,Django Templates,我使用Django查询作为: sports.PYST.objects.using( 'sports-data' ).all().values('season','player','team').annotate(max_count = Max('punt_long') ).query 它给出的o/p类似于: SELECT `PYST`.`SEASON`, `PYST`.`PLAYER`, `PYST`.`TEAM`, MAX(`PYST`.`PUNT_LONG`) AS `max_count
sports.PYST.objects.using( 'sports-data' ).all().values('season','player','team').annotate(max_count = Max('punt_long') ).query
它给出的o/p类似于:
SELECT `PYST`.`SEASON`, `PYST`.`PLAYER`, `PYST`.`TEAM`, MAX(`PYST`.`PUNT_LONG`) AS `max_count` FROM `PYST` GROUP BY `PYST`.`SEASON`, `PYST`.`PLAYER`, `PYST`.`TEAM` ORDER BY NULL
我所期望的是:
select season,player,team,max(punt_long)as punt_long from PYST group by season
有人能在这方面提供帮助或需要任何其他信息吗?我认为如果没有以下任何一项,这都是不可能的:
from django.db.models import Max, Q
from operator import __or__ as OR
result_dict = Score.objects.values('season').annotate(Max('punt'))
q = [Q(season=row['season']) & Q(punt=row['punt__max']) for row in result_dict]
qs = Score.objects.filter(reduce(OR, q))
有关更多详细信息,请查看此链接:
虽然为时已晚,但我希望它对今天的人有用:
Model.objects.filter(name__in=["foo", "foo1"]).values('last_name')\
.order_by('id')\
.annotate(total=Count('id')).values('first_name')
生成以下查询:
SELECT "models_model"."first_name", COUNT("models_model"."id") AS "total" FROM "models_model" WHERE "models_model"."name" IN (...) GROUP BY "models_model"."last_name", "models_model"."author_id" ORDER BY "models_model"."id" ASC
我不想使用原始sql。你能给第二个举个例子吗。