How to use Python type hints with Django QuerySet?

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

    You actually can do what you want if you import the annotations module:

    from __future__ import annotations
    from django.db import models
    from django.db.models.query import QuerySet
    
    class MyModel(models.Model):
        pass
    
    def my_function() -> QuerySet[MyModel]:
        return MyModel.objects.all()
    

    Neither MyPy nor the Python interpreter will complain or raise exceptions on this (tested on python 3.7). MyPy will probably be unable to type-check it, but if all you want is to document your return type, this should be good enough.

提交回复
热议问题