TypeError: 'type' object is not subscriptable with prefetch_related

I’m trying to return a specific queryset using prefetch_related to optimize future queries, but I’m encountering an issue. When I don’t specify a return type, the code works fine. However, I want to understand the actual return type and what’s happening when I specify the return type as QuerySet[ABCInstance].

Here’s the code I’m working with:

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")

In this case:

  • xyz_instance has a one-to-many relationship with abc_instances.
  • abc_instances has a one-to-many relationship with cde_instances.

My current environment:

  • Python 3.6.7
  • Django 2.0.2

I’m expecting the return type to be ABCInstance, but since the query involves prefetching related data, the actual return type is different. I’d like to understand what the actual return type is in this case.

Python 3.6.7

In Python-3.6, types are indeed not subscriptable, so tuple[int, int] was not allowed as expressions. Since with the Type Hinting Generics In Standard Collections proposal [pep-585], for certain types that are subclasses of Iterable for example, one can subscript the type. A QuerySet is a subclass of collections.abc.Iterable (because it implements __iter__), so you can indeed write QuerySet[SomeType], but only since .

You should upgrade the Python version to at least Python-3.9, or you use -> QuerySet instead, without subscripting the QuerySet type.

Вернуться на верх