Home > Net >  Group results from QuerySet
Group results from QuerySet

Time:09-26

I am trying to collect the scores of each football match into a single list of the team points across the season.

something like {1,3,3,3,1,....}

My model is:

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>,... >]

The data added to the model is not in order, for example:

Red Team 1 ...
Red Team 3 ...
Blue Team 1 ...
Gren Team 1 ...
Red Team 3...

So i'm not sure how I collect each point for each team and group it together.

I've tried

points = MatchScores.objects.filter(profile__user=profile.user)
all_points = []

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

but this returns TypeError: argument of type MatchScores' is not iterable

CodePudding user response:

You cannot iterate the object, so the line: if "points" in team: is not valid. To get an object's field you don't treat it as it's dictionary. For objects you use .. Change to this:

for team in points:
    if team.points:    # it will be False if points == 0
        all_points.append(team.points)
  • Related