Saturday, 21 May 2022

Type annotations for Django models

I'm working on a Django project. Since this is a new project, I want to have it fully annotated with python 3.6+ type annotations. I'm trying to annotate models, but I struggle to find a good method for that.

Let's take the IntegerField as an example. I see two choices for annotating it:

# number 1
int_field: int = models.IntegerField()

# number 2
int_field: models.IntegerField = models.IntegerField()

Number 1 fails in mypy:

Incompatible types in assignment (expression has type "IntegerField[<nothing>, <nothing>]", variable has type "int")

Number 2 is OK for mypy, but IDE's as PyCharm are not able to resolve it and are often complaining about wrong types used.

Are there any best practices to correctly annotate the models, which will satisfy mypy and IDE's?



from Type annotations for Django models

No comments:

Post a Comment