Python / Django-Mypy:表达式的类型为“ Type [ModelInstance]”,变量的类型为“ ModelInstance”

问题描述 投票:1回答:1

我正在开发一个为前端提供GraphQL api的Django应用。我正在使用mypy进行类型检查,并且在运行mypy时遇到了我不理解的错误

运行时出现以下错误:

api/schema.py:50: error: Incompatible types in assignment (expression has type "Type[Academy]", variable has type "Academy")
api/schema.py:57: error: Incompatible types in assignment (expression has type "Type[School]", variable has type "School")
api/schema.py:64: error: Incompatible types in assignment (expression has type "Type[AcademyGroup]", variable has type "AcademyGroup")

这是mypy正在检查的代码

class AcademyType(DjangoObjectType):
    class Meta:
        model: Academy = Academy
        filter_fields: List[str] = ['name', 'domain', 'slug']
        interfaces: Tuple = (relay.Node,)


class SchoolType(DjangoObjectType):
    class Meta:
        model: School = School
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)


class AcademyGroupType(DjangoObjectType):
    class Meta:
        model: AcademyGroup = AcademyGroup
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)

所以一直失败的行是model: AcademyGroup = AcademyGroup的变体,但这只是在我的代码中不断发生的'Django模型为类型'定义(似乎并没有产生错误)

因此,我不太确定自己在这里做错了什么,因此将不胜感激。

python django mypy
1个回答
0
投票

model属性的类型不是类本身,而是Type。确实,如果您说model = Academy,则model的类型是type(model) == type(Academy) == Type,的确,AcademynotAcademy object,它是对类的引用,此类的类型是Type的(子类)。您还可以使用Type[…] [python-doc]指定类型的(base-)类,因此Type[…]表示它是Type[C]的类型,或者是C的子类:

因此,您应将其注释为:

C
© www.soinside.com 2019 - 2024. All rights reserved.