我有“ Club”类和“ Match”类两个模型,并且具有俱乐部的外键 但是我不能通过“匹配”类中的“ score_local”和“ score_visitor”来增加“ Club”类中的“获胜”字段(或平局或输掉)。 我该怎么办
class Club(models.Model):
league_names = models.ForeignKey(League, on_delete= models.CASCADE, related_name='club')
name = models.CharField(max_length=100)
logo = models.ImageField(upload_to='media/core', max_length=255, null=True, blank=True)
year_of_establishment = models.IntegerField(default=1900)
won = models.IntegerField(default=0)
draw = models.IntegerField(default=0)
lost = models.IntegerField(default=0)
def CalcPoints(self):
return self.won*3 + self.draw
total_points = property(CalcPoints)
class Match(models.Model):
play_date = models.DateTimeField('play date')
occasion = models.ForeignKey(League, on_delete=models.CASCADE, related_name='match')
club_visitor = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='match_club_visitor')
club_local = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='match_club_local')
score_visitor = models.IntegerField()
score_local = models.IntegerField()
答案 0 :(得分:1)
即使在同一模型上,也无法在字段之间建立关系,但是您可以覆盖Match中的save
方法,您可以实现一个signal处理函数,在每个{{1 }}被保存。
match
答案 1 :(得分:0)
您将需要以某种方式更新模型的字段。
我会建议类似的东西
首先,编写一个从数据库为您提供俱乐部的功能:
def get_clubs(local_club_id, visitor_club_id):
local_club = Club.objects.filter(pk=self.local_club_id)[0]
visitor_club = Club.objects.filter(pk=self.visitor_club_id)[0]
return local_club, visitor_club
然后,您可以适当地(在您的views.py
中)更新胜负:
def update_scores(request):
match = request.match
club_local, club_visitor = get_clubs(match.club_local.pk, match.club_visitor.pk)
if match.score_local > match.score_visitor:
# home team won
club_local.update(won=match.club_local.won + 1)
club_visitor.update(lost=match.club_visitor.lost + 1)
elif match.score_visitor > match.score_local:
# away team won
club_visitor.update(won=match.club_visitor.won + 1)
club_local.update(lost=match.club_local.lost + 1)
else:
# it's a draw
club_local.update(draw=match.club_local.draw + 1)
club_visitor.update(draw=match.club_visitor.draw + 1)
此后,您的属性函数应会按预期工作。