From 05116bff2abe070fb29c13756778e2db252ece76 Mon Sep 17 00:00:00 2001 From: Petter Friberg Date: Thu, 7 Dec 2023 20:54:28 +0100 Subject: [PATCH 1/2] Include ModelBase subclasses in plugin base class hook condition --- mypy_django_plugin/lib/helpers.py | 7 ++++++- tests/typecheck/models/test_metaclass.yml | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/mypy_django_plugin/lib/helpers.py b/mypy_django_plugin/lib/helpers.py index 3e2c9f689..c1866780d 100644 --- a/mypy_django_plugin/lib/helpers.py +++ b/mypy_django_plugin/lib/helpers.py @@ -474,4 +474,9 @@ def resolve_lazy_reference( def is_model_type(info: TypeInfo) -> bool: - return info.metaclass_type is not None and info.metaclass_type.type.fullname == fullnames.MODEL_METACLASS_FULLNAME + return info.metaclass_type is not None and ( + # Using the model metaclass shipped by Django + info.metaclass_type.type.fullname == fullnames.MODEL_METACLASS_FULLNAME + # Using a custom model metaclass that inherits above + or info.metaclass_type.type.has_base(fullnames.MODEL_METACLASS_FULLNAME) + ) diff --git a/tests/typecheck/models/test_metaclass.yml b/tests/typecheck/models/test_metaclass.yml index a26ba43fe..865f4fad7 100644 --- a/tests/typecheck/models/test_metaclass.yml +++ b/tests/typecheck/models/test_metaclass.yml @@ -73,3 +73,25 @@ class Concrete3(Concrete2): ... + +- case: test_custom_model_base_metaclass + main: | + from myapp.models import This, Other + + this = This(field=Other()) + reveal_type(this.field) # N: Revealed type is "myapp.models.Other" + installed_apps: + - myapp + files: + - path: myapp/__init__.py + - path: myapp/models.py + content: | + from django.db import models + from django.db.models.base import ModelBase + + class MyBase(ModelBase): ... + class MyModel(models.Model, metaclass=MyBase): ... + + class Other(MyModel): ... + class This(MyModel): + field = models.ForeignKey(Other, on_delete=models.CASCADE) From 983a7520df97f78de4243075e943119dc49afcdc Mon Sep 17 00:00:00 2001 From: Petter Friberg Date: Fri, 8 Dec 2023 10:58:24 +0100 Subject: [PATCH 2/2] fixup! Include ModelBase subclasses in plugin base class hook condition --- mypy_django_plugin/lib/helpers.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/mypy_django_plugin/lib/helpers.py b/mypy_django_plugin/lib/helpers.py index c1866780d..8e226a231 100644 --- a/mypy_django_plugin/lib/helpers.py +++ b/mypy_django_plugin/lib/helpers.py @@ -474,9 +474,4 @@ def resolve_lazy_reference( def is_model_type(info: TypeInfo) -> bool: - return info.metaclass_type is not None and ( - # Using the model metaclass shipped by Django - info.metaclass_type.type.fullname == fullnames.MODEL_METACLASS_FULLNAME - # Using a custom model metaclass that inherits above - or info.metaclass_type.type.has_base(fullnames.MODEL_METACLASS_FULLNAME) - ) + return info.metaclass_type is not None and info.metaclass_type.type.has_base(fullnames.MODEL_METACLASS_FULLNAME)