Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]
?
For example, we have model:
This is an improved helper class of Or Duan.
from django.db.models import QuerySet
from typing import Iterator, TypeVar, Generic
_Z = TypeVar("_Z")
class QueryType(Generic[_Z], QuerySet):
def __iter__(self) -> Iterator[_Z]: ...
This class is used specifically for QuerySet
object such as when you use filter
in a query.
Sample:
from some_file import QueryType
sample_query: QueryType[SampleClass] = SampleClass.objects.filter(name=name)
Now the interpreter recognizes the sample_query
as a QuerySet
object and you will get suggestions such as count()
and while looping through the objects, you will get suggestions for the SampleClass
Note
This format of type hinting is available from python3.6
onwards.
You can also use django_hint which has hinting classes specifically for Django.