Let's say we have the following models:
class Site(models.Model):
# This is djangos build-in Site Model
pass
class Organization(models.Model):
site = models.OneToOneField(Site)
And if I use this somewhere in some other class:
organization = self.site.organization
Then mypy complains:
Site has no attribute "organization"
How can I make mypy happy here?
Django adds backwards relations at runtime which aren't caught by
mypy
which only does static analysis.To make
mypy
happy (and to make it work with your editor's autocomplete) you need to add an explicit type hint toSite
:Using quotes around the type is needed since we are doing a forward reference to
Organization
before it has been defined.For foreign keys and many-to-many relationships, you can do the same thing, but using a
QuerySet
type hint instead:EDIT: There is a django-stubs package which is meant to integrate with
mypy
, however I haven't used it personally. It may provide a solution for this without having to explicitly add type hints to models.