我正在处理Django项目,并且正在使用mypy进行类型检查。 为了启用django的类型检查,我使用了django-stubs软件包。
这很好用,但是我现在遇到了一种情况,mypy抛出了两个我似乎无法解决的错误:
Item "None" of "Optional[Season]" has no attribute "league"
Incompatible type for "league" of "Match" (got "Union[ForeignKey[Union[League, Combinable], League], Any]", expected "Union[League, Combinable, None]")
对于以下代码,将引发这些错误。我正在初始化(但不创建/保存到数据库)Match
模型的实例。
match = Match(
home_team=home_team,
away_team=away_team,
league=home_team.seasons.last().league,
season=home_team.seasons.all().last(),
)
所涉及的模型如下所示:
class League(models.Model):
name = models.CharField(max_length=200)
class Season(models.Model):
first_year = models.PositiveIntegerField()
second_year = models.PositiveIntegerField()
league = models.ForeignKey(
League, related_name="seasons", on_delete=models.CASCADE
)
class Team(models.Model):
name = models.CharField(max_length=200)
seasons = models.ManyToManyField(Season, related_name="teams")
class Match(models.Model):
league = models.ForeignKey(
League, related_name="matches", on_delete=models.CASCADE
)
season = models.ForeignKey(
Season, related_name="matches", on_delete=models.CASCADE
)
home_team = models.ForeignKey(
Team, related_name="home_matches", on_delete=models.CASCADE
)
away_team = models.ForeignKey(
Team, related_name="away_matches", on_delete=models.CASCADE
)
我了解第一个错误(Item "None" of "Optional[Season]" has no attribute "league"
)
Seasons
指的是ManyToMany
字段,当然可以为None。
我看不到第二个错误在做什么。
我的主要问题是我不确定解决这些错误的规范方法。 ManyToMany字段始终可以返回可选值,但是不使用它们显然是错误的答案。我可以在代码中附加一些# type: ignore
语句,但是那只是在绕过问题而不是解决问题。
有人知道我在做什么错吗?如果是这样,在这种情况下使用mypy的正确方法是什么?