A
A
Alexey2017-02-23 19:45:51
Django
Alexey, 2017-02-23 19:45:51

How to specify the type of records in Django QuerySet in Python type hints?

Is it possible, using Type Hints in Python, to specify the type of entries in a Django QeurySet? Something like QuerySet(SomeModel)?
For example, we have a model:

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

and we want to pass as a parameter to some QuerySet function with records of this model:
def somefunc(rows: QuerySet):
    pass

But how to specify that there should be not just a QuerySet, but a QuerySet with records of the SomeModel model? That is, if you passed not a QuerySet, but a list, then you could do this:
def somefunc(rows: List[SomeModel]):
    pass

but what about QuerySet?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Podgursky, 2017-03-02
@kmmbvnr

At the moment this is not possible.
Here is the relevant ticket - https://github.com/python/mypy/issues/1310

S
sobolevn, 2019-08-27
@sobolevn

You need to use `django-stubs` .
Inside type stubs and mypy's own plugins to make everything work correctly.
Tutorial: https://sobolevn.me/2019/08/typechecking-django-and-drf

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question