Search code examples
djangodjango-modelsormmypy

Mypy with Django: type[MyModel] has no attribute "objects" [attr-defined]


After coding my Django model and adding a method which uses the "objects" manager, Mypy continues to show the error (command: "mypy ."):

models.py:168: error: "type[MyModel]" has no attribute "objects"  [attr-defined]

How to solve that?


Solution

  • I found a solution reading some issues on Github (https://github.com/typeddjango/django-stubs/issues/1684). There are different approaches:

    So for example the final result will be:

    class Action(models.Model):
    class Meta:
        verbose_name = _("Action")
        verbose_name_plural = _("Actions")
    
    # useless Mypy type hinting. Avoids errors in Mypy check
    objects: models.Manager["Action"]