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?
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
In Django, above argument is called field lookups argument, the field lookups argument's format should be fieldname__lookuptype=value. Please note the double underscore ( __ ) between the field name(depe_desc) and lookup type keyword contains.
Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With