How to use Python type hints with Django QuerySet?

后端 未结 9 884
一个人的身影
一个人的身影 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:46

    from typing import (TypeVar, Generic, Iterable, Optional)
    from django.db.models import Model
    from django.db.models import QuerySet
    _T = TypeVar("_T", bound=Model)
    
    
    class QuerySetType(Generic[_T], QuerySet):
        def __iter__(self) -> Iterable[_T]:
            pass
    
        def first(self) -> Optional[_T]:
            pass
    

提交回复
热议问题