python - rewrite sql query using Django db Api -
these models in django
class match(models.model): team_a = models.foreignkey("team", related_name="team_a") equipo_b = models.foreignkey("team", related_name="team_b") goals_team_a = models.integerfield(default=0) goals_team_b = models.integerfield(default=0) winner_team = models.foreignkey("team", related_name="winner_team", null=true) match_type = models.charfield(choices=match_type_choices, max_length=100, null=false) match_played = models.booleanfield(default=false) date = models.datefield() class team(models.model): name = models.charfield(max_length=200) group = models.charfield(choices=group_choices, max_length=1, null=false) matches_played = models.integerfield(default=0) matches_won = models.integerfield(default=0) matches_lost = models.integerfield(default=0) matches_tied = models.integerfield(default=0) goals_in_favor = models.integerfield(default=0) goals_agaiinst = models.integerfield(default=0) points = models.integerfield(default=0) url_flag = models.charfield(max_length=500)
and have following sentence in raw sql:
select (select sum(goals_team_a) match team_a_id=9) + (select sum(goals_team_b) match team_b_id=9) goals_in_favor, (select sum(goals_team_b) match team_a_id=9) + (select sum(goals_team_a) match team_b_id=9) goles_against ;
i'm looking efficient way rewrite query using django queryset api, can't find way it, have clue have use annotate() function, don't know how.
finally came resolution:
def count_goals_in_favor(team): goals_home = partido.objects.filter(team_a=team).extra( select={"total_goals": "sum(goals_team_a)"}).values("total_goals") goals_away = partido.objects.filter(team_b=team).extra( select={"total_goals": "sum(goals_team_b)"}).values("total_goals") return goals_home[0]['total_goals'] + goals_away[0]['total_goals'] def count_goals_against(team): goals_home = partido.objects.filter(team_a=team).extra( select={"total_goals": "sum(goals_team_b)"}).values("total_goals") goals_away = partido.objects.filter(team_b=team).extra( select={"total_goals": "sum(goals_team_a)"}).values("total_goals") return goals_home[0]['total_goals'] + goals_away[0]['total_goals'] class team(models.model): pass # code put in question def goals_difference(self): return self.goals_in_favor - self.goals_against class match(models.model): pass # code put in question def save(self): self.team_a.goals_in_favor = count_ goals_in_favor(self.team_a) self.team_a.goals_against = count_goals_against(self.team_a)
Comments
Post a Comment