Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django中选择具有单个group by的多个字段_Python_Django_Django Templates - Fatal编程技术网

Python 在django中选择具有单个group by的多个字段

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

我使用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` 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

有人能在这方面提供帮助或需要任何其他信息吗?

我认为如果没有以下任何一项,这都是不可能的:

  • 原始sql
  • 用于检索由聚合结果过滤的对象的附加查询(这在Q对象的帮助不大的情况下是可能的)
  • 编辑1:

    关于解决方案2。这也许不是最好的主意,但这是我能想到的最快的办法:

    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。你能给第二个举个例子吗。