How to use Python type hints with Django QuerySet?

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

    One solution may be using Union typing class.

    from typing import Union, List
    from django.db.models import QuerySet
    from my_app.models import MyModel
    
    def somefunc(row: Union[QuerySet, List[MyModel]]):
        pass
    

    Now when you slice the row argument it will know that the returned type is either another list of MyModel or an instance of MyModel, whilst also hinting that the methods of the QuerySet class are available on the row argument too.

提交回复
热议问题