How to use Python type hints with Django QuerySet?

后端 未结 9 894
一个人的身影
一个人的身影 2021-01-30 08:25

Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]?

For example, we have model:

9条回答
  •  不知归路
    2021-01-30 08:39

    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.

提交回复
热议问题