Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python type hints with Django QuerySet?

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?

like image 341
Алексей Голобурдин Avatar asked Feb 22 '17 16:02

Алексей Голобурдин


People also ask

What is the type of Django 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.

What is __ in Django ORM?

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.

Do Python type hints improve performance?

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.


1 Answers

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.

like image 64
A. J. Parr Avatar answered Sep 29 '22 03:09

A. J. Parr