I’m trying to enable type hints for my Django REST project. I installed
djangorestframework-stubs and I have the following
[mypy] plugins = mypy_django_plugin.main mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = "core.settings.base"
Some of the type hints do work; for example, if I have a variable inside of a method whose type is a model class, I get hints when I try to access a field or method defined on it.
However, if I try to access a Django-specific field on the model, for example a reverse relation, that does not typecheck and gives me an error. Moreover, if I try to access fields on a related model of my model variable, the related object has type
For example, with these two models:
class User(models.Model): name = models.TextField() role = models.ForeignKey(Role) # definition of Role model not relevant class Badge(models.Model): user = models.ForeignKey(User, related_name="badges")
then this will happen:
u: User = get_user() print(u.name) # correctly hinted and typechecks print(u.badges.all()) # type error print(u.role.pk) # no hint on role.pk, role is Any
How do I get my project to correclty type check all the Django-specific features such as foreign key fields, querysets, and reverse relationships?