Django循环使用模型.PositiveIntegerField瓦里亚布

2024-04-25 17:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

class Zapas(models.Model):
tym_domaci = models.ForeignKey(Tym, on_delete=models.CASCADE)
tym_hoste = models.ForeignKey(Tym, on_delete=models.CASCADE)
datum = models.DateTimeField('datum zapasu')
goly_domaci = models.PositiveIntegerField(default=0)
goly_hoste = models.PositiveIntegerField(default=0)

for x in range (goly_domaci):
    strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_domaci})
    nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_domaci})

for x in range (goly_hoste):
    strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_hoste})
    nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_hoste})

我要做的是,为每支球队加载所有进球的球员和助攻的球员(如果有的话)。问题是,我不能在for循环中使用goly\u domaci和goly\u hoste,因为它们是正整数域而不是整数。有没有办法把正整数域转换成整数?或者我可以像这样使用for循环吗?我是python和Django的新手,所以我真的不知道如何解决它。感谢您的帮助:-)


Tags: totrueforonmodelsdeletecascadechoices
1条回答
网友
1楼 · 发布于 2024-04-25 17:11:09

不,这不是原因。这段代码没有意义;您不能这样动态地定义字段。字段依赖于数据库中的列,因此模型必须具有固定数量的字段。而goly_domaci本身就是一个字段,此时它没有值;它只有在从实际实例访问时才有值,此时定义其他字段为时已晚。你知道吗

但这不是你想做的。为同一目标模型定义所有这些单独的外键是没有意义的。您要做的是为目标定义一个单独的模型,它指向这个模型(我假设Zapas意味着游戏)。你知道吗

class Goal(models.Model):
    game = models.ForeignKey(Zapas)
    team = models.ForeignKey(Tym, on_delete=models.CASCADE)
    strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE)
    nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True)

然后您可以删除goly_domacigoly_hoste字段,因为您可以在需要显示它们时计算它们:

goly_hoste = my_zpas.goal_set.filter(team=my_zpas.tym_hoste).count()
goly_domaci = my_zpas.goal_set.filter(team=my_zpas.tym_domaci).count()

相关问题 更多 >

    热门问题