You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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版本,有两种可行的类型注解方式:

  1. 字符串形式的前向引用(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")
    
  2. 使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:22:07