首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自QuerySet的分组结果

来自QuerySet的分组结果
EN

Stack Overflow用户
提问于 2022-09-25 08:08:13
回答 1查看 20关注 0票数 0

我正试图把每场足球比赛的分数整理成一个球队在整个赛季中得分的单子。

类似{1,3,3,3,1,.}

我的模型是:

代码语言:javascript
复制
class MatchScores(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) 
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True)
    game = models.ForeignKey('game', on_delete=models.CASCADE, blank=True)
    points = models.SmallIntegerField(blank=True, null=True)
    ...

    def __str__(self):
        return str(self.team)
    
    class Meta:
        verbose_name = "Match Scores"




<QuerySet [<MatchScores: Red Team>, <MatchScores: Blue Team>,... >]

添加到模型中的数据不符合要求,例如:

代码语言:javascript
复制
Red Team 1 ...
Red Team 3 ...
Blue Team 1 ...
Gren Team 1 ...
Red Team 3...

所以我不知道我是如何为每支球队收集每一分并将其组合在一起的。

我试过了

代码语言:javascript
复制
points = MatchScores.objects.filter(profile__user=profile.user)
all_points = []

for team in points:
    if "points" in team:
        all_points.append(team["points"])

但这会返回TypeError: argument of type MatchScores' is not iterable

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-25 08:31:36

不能迭代对象,因此行:if "points" in team:无效。要得到一个对象的字段,不要把它当作字典来处理。对于对象,则使用.。改为:

代码语言:javascript
复制
for team in points:
    if team.points:    # it will be False if points == 0
        all_points.append(team.points)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73842934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档