How to use Python type hints with Django QuerySet?

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

    I've found myself that using typing.Sequence to solve a similar issue:

    from typing import Sequence
    
    
    def print_emails(users: Sequence[User]):
        for user in users:
            print(user.email)
    
    
    users = User.objects.all()
    
    
    print_emails(users=users)
    

    As far as I know from docs:

    A Sequence is anything that supports len() and .getitem(), independent of its actual type.

提交回复
热议问题