Update 2023
In django_hint 0.3.0 you can extend your model and the return type of the common functions of objects
such as filter
, get
, etc. will be automatically detected.
from django_hint import StandardModelType
class SampleModel(models.Model, StandardModelType['SampleModel']):
name: str = models.CharField(max_length=300)
Original Answer
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.
Disclaimer: I am the author of django_hint