两个如何同时在其他模型中保存模型的某些字段

时间:2015-04-09 16:08:56

标签: django django-models

我有这个型号:

class Match2x1(models.Model):
    league = models.ForeignKey(League)
    country = models.ForeignKey(Country)
    date = models.DateTimeField()
    team_a = models.ForeignKey(Teams)
    team_b = models.ForeignKey(Teams,related_name="equipos")
    ending_hour = models.TimeField()
    status = models.BooleanField(default=False)

    def __str__(self):
        match = "%s VS %s"%(self.team_a,self.team_b)
        return match

我希望在此模型中保存这些模型的同时保存team_a和team_b字段:

class TeamsMatch(models.Model):
    team = models.CharField(max_length=100)

    def __str__(self):
        return self.team

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你是如何添加这个匹配的?你粘贴文字了吗?或者您是否必须从列表中选择团队?

您可以使用:

def save(self, *args, **kwargs):
     team_1 = TeamsMatch(self.team_a)
     team_2 = TeamsMatch(self.team_b)
     team_1.save()
     team_2.save()
     super(Match2x1, self).save(*args, **kwargs)