使用prefetch_related指定QuerySet[ABCInstance]返回类型触发TypeError咨询
问题解析与解决方案
错误原因
你碰到的TypeError: 'type' object is not subscriptable是两个因素共同导致的:
- Python 3.6不支持原生的泛型下标语法(比如
QuerySet[ABCInstance]),这种写法要到Python 3.9才通过PEP 585正式支持。 - Django 2.0.2的
QuerySet类本身并非泛型类,无法直接通过下标指定内部元素类型。
实际返回类型
这段代码返回的是django.db.models.query.QuerySet的实例,该QuerySet包含的元素是ABCInstance模型对象。调用prefetch_related("cde_instances")只是预先加载了关联的cde_instances数据以避免N+1查询问题,不会改变QuerySet本身的类型。
正确的类型注解写法
针对你的Python和Django版本,有两种可行的类型注解方式:
- 字符串形式的前向引用(Python 3.6支持该特性):
def _fetch_abc_instances(self) -> "QuerySet[ABCInstance]": # Prefetch related "cde_instances" to avoid N+1 query issues return self.xyz_instance.abc_instances.prefetch_related("cde_instances") - 使用
typing.Iterable标注:
因为QuerySet是可迭代对象,你可以用Iterable来标注元素类型:from typing import Iterable def _fetch_abc_instances(self) -> Iterable[ABCInstance]: # Prefetch related "cde_instances" to avoid N+1 query issues return self.xyz_instance.abc_instances.prefetch_related("cde_instances")
内容的提问来源于stack exchange,提问作者Gokhul
相关产品推荐
相关产品推荐

