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?
I found a solution reading some issues on Github (https://github.com/typeddjango/django-stubs/issues/1684). There are different approaches:
use the _default_manager attribute, but this is a protected attribute and it is not convenient (you will have also a linter warning): https://docs.djangoproject.com/en/4.2/topics/db/managers/#django.db.models.Model._default_manager
annotate the model class with a useless objects hinting, like 'objects: models.Manager["MyModel"]'
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"]