本文介绍了在django中选择单个组的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用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
我的预期:
选择季节,球员,球队,最大(punt_long)作为punt_long从PYST组按季节
$
解决方案p $ p
p>我不认为这是可能没有:
- raw sql
- 其他查询检索通过聚合结果过滤的对象(可以在Q对象的帮助下进行)
编辑1:
关于解决方案号2.这仍然可能不是最好的想法,但这是我能想出的最快的:
from django.db.models import Max,Q
从运算符导入__or__作为OR
result_dict = Score.objects.values('season')。annotate(Max('punt'))
q = [Q(season = row [季节'])&对于result_dict中的行,Q(punt = row ['punt__max'])
qs = Score.objects.filter(reduce(OR,q))
查看此链接了解更多详情:
I used Django query as :
sports.PYST.objects.using( 'sports-data' ).all().values('season','player','team').annotate(max_count = Max('punt_long') ).query
It gives o/p like :
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
What I expected :
select season,player,team,max(punt_long)as punt_long from PYST group by season
Can any one help on this or need any additional information ?
解决方案I don't think this is possible without either:
- raw sql
- additional query to retrieve objects filtered by aggregation result (which is possible with little help from Q objects)
Edit 1:
Regarding solution no 2. This still may be not the best idea, but it's the quickest I could come up with:
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))
Check out this link for more details:http://css.dzone.com/articles/best-way-or-list-django-orm-q
这篇关于在django中选择单个组的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!