3

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

任何人都可以对此提供帮助或需要任何其他信息吗?

4

2 回答 2

1

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

  1. 原始 sql
  2. 用于检索按聚合结果过滤的对象的附加查询(在 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))

查看此链接了解更多详情: http ://css.dzone.com/articles/best-way-or-list-django-orm-q

于 2013-07-26T16:40:18.303 回答
0

为时已晚,但我希望它今天对某人有用:

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
于 2017-07-16T17:22:06.950 回答