How to use Python type hints with Django QuerySet?

Алексей Голобурдин picture Алексей Голобурдин · Feb 22, 2017 · Viewed 21.6k times · Source

Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]?

For example, we have model:

class SomeModel(models.Model):
    smth = models.IntegerField()

And we want to pass QuerySet of that model as param in func:

def somefunc(rows: QuerySet):
    pass

But how to specify type of records in QuerySet, like with List[SomeModel]:

def somefunc(rows: List[SomeModel]):
    pass

but with QuerySet?

Answer

A. J. Parr picture A. J. Parr · Jun 2, 2017

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.