How to use Python type hints with Django QuerySet?

后端 未结 9 900
一个人的身影
一个人的身影 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条回答
  •  旧时难觅i
    2021-01-30 08:43

    IMHO, the proper way to do it is to define a type that inherits QuerySet and specify a generic return type for the iterator.

        from django.db.models import QuerySet
        from typing import Iterator, TypeVar, Generic, Optional
    
        T = TypeVar("T")
    
    
        class QuerySetType(Generic[T], QuerySet):  # QuerySet + Iterator
    
            def __iter__(self) -> Iterator[T]:
                pass
    
            def first(self) -> Optional[T]:
                pass
    
            # ... add more refinements
    
    
    

    Then you can use it like this:

    users: QuerySetType[User] = User.objects.all()
    for user in users:
       print(user.email)  # typing OK!
    user = users.first()  # typing OK!
    
    

提交回复
热议问题