How to use Python type hints with Django QuerySet?

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

    I made this helper class to get a generic type hint:

    from django.db.models import QuerySet
    from typing import Iterator, Union, TypeVar, Generic
    
    T = TypeVar("T")
    
    class ModelType(Generic[T]):
        def __iter__(self) -> Iterator[Union[T, QuerySet]]:
            pass
    

    Then use it like this:

    def somefunc(row: ModelType[SomeModel]):
        pass
    

    This reduces the noise everytime I use this type and it make it usable between models (like ModelType[DifferentModel]).

提交回复
热议问题