我有一个模型类
class PlayerScore(models.Model):
number=models.IntegerField()
points=models.FloatField(default=0)
player=models.ForeignKey('Player')
我想将数据分组为数字字段的相同值。 对于前如果db中的数据是
number | points | player_id
-------+--------+----------
1 | 45 | 1
1 | 68 | 2
2 | 79 | 3
2 | 70 | 4
我的查询应该返回
[{"number":1, "records": [{"points":45,"player_id":1},{"points":68,"player_id":2}]},
{"number":2, "records" :[{"points":79,"player_id":3},{"points":70,"player_id":4}]}]
请建议如何为此编写查询??
答案 0 :(得分:2)
如果要在数据库级别上对其进行计算,则只能使用原始数据库查询来完成。但你也可以在python中实现它。
首先,获取按number
排序的所有记录的列表:
PlayerScore.objects.order_by('number')
现在,使用values
将所有对象作为字典,因此我们可以更方便地将它们组合在一起:
PlayerScore.objects.order_by('number').values() # or you can list only relevant fields inside values
现在,使用来自itertools的groupby,我们可以构建我们的结果:
from itertools import groupby
values = [
{'number': k, 'records': list(g)} for k, g in # we are converting iterator returned from groupby into desired list of dictionaries
groupby(PlayerScore.objects.order_by('number').values(), lambda x: x['number'])
]