Django - 搜索为每个id创建的最后一个对象,并保持其他字段的总和

时间:2018-03-28 17:53:16

标签: django

我正在进行查询,我想获取与特定团队相关的所有游戏列表,但我希望字段&#34; date_created&#34;,仅保存最后一个日期。< / p>

所以这是我的问题:

 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-08-24T00:00:00",
            "points": "10",
        },
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-09-18T00:00:00",
            "points": "10",
        },
        {
            "donation__sponsor": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2016-06-20T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2017-11-10T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "10",
        }
]

我的愿望是:

 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-09-18T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "10",
        }
]

我的最终目标是查询另一个字段,该字段对内部属性求和 像这样:

 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-08-24T00:00:00",
            "points": "30",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "20",
        }
]

这是我最接近的想法:

#I get the sum of points with the name, but missing last date_created
qs = Game.filter(id=1).values('first_name', 'last_name', 'date_created').annotate(points = Sum('points')

使用.latest()我只获得最后一场比赛,而不是最后一场与每场比赛相关的比赛。 我认为我需要做两个查询集,然后是一些联合,但是idk

1 个答案:

答案 0 :(得分:3)

试试这个,

from django.db.models import Sum, Max

Game.objects.values('id').annotate(points=Sum('point'), date_created=Max('date_created'))


此表单等同于原始sql,

Select id,SUM(point) as points, MAX(date_created) as date_created from GameTable Group By id