diff --git a/mypy_django_plugin/main.py b/mypy_django_plugin/main.py index 880c745..ff40ec6 100644 --- a/mypy_django_plugin/main.py +++ b/mypy_django_plugin/main.py @@ -105,6 +105,12 @@ def extract_and_return_primary_key_of_bound_related_field_parameter(ctx: Attribu return ctx.default_attr_type +def return_integer_type_for_id_for_non_defined_primary_key_in_models(ctx: AttributeContext) -> Type: + if isinstance(ctx.type, Instance) and ctx.type.type.has_base(helpers.MODEL_CLASS_FULLNAME): + return ctx.api.named_generic_type('builtins.int', []) + return ctx.default_attr_type + + class ExtractSettingType: def __init__(self, module_fullname: str): self.module_fullname = module_fullname @@ -234,6 +240,9 @@ class DjangoPlugin(Plugin): if module == 'builtins.object' and name in metadata: return ExtractSettingType(module_fullname=metadata[name]) + if fullname == 'builtins.object.id': + return return_integer_type_for_id_for_non_defined_primary_key_in_models + return extract_and_return_primary_key_of_bound_related_field_parameter diff --git a/mypy_django_plugin/plugins/models.py b/mypy_django_plugin/plugins/models.py index 2e354a2..ff2ac07 100644 --- a/mypy_django_plugin/plugins/models.py +++ b/mypy_django_plugin/plugins/models.py @@ -8,7 +8,6 @@ from mypy.plugin import ClassDefContext from mypy.plugins.common import add_method from mypy.semanal import SemanticAnalyzerPass2 from mypy.types import AnyType, Instance, NoneTyp, TypeOfAny - from mypy_django_plugin import helpers from mypy_django_plugin.helpers import iter_over_assignments @@ -161,7 +160,7 @@ class AddIdAttributeIfPrimaryKeyTrueIsNotSet(ModelClassInitializer): and self.api.parse_bool(rvalue.args[rvalue.arg_names.index('primary_key')])): break else: - self.add_new_node_to_model_class('id', self.api.builtin_type('builtins.int')) + self.add_new_node_to_model_class('id', self.api.builtin_type('builtins.object')) class AddRelatedManagers(ModelClassInitializer): diff --git a/test-data/typecheck/fields.test b/test-data/typecheck/fields.test index c3c2d21..da71746 100644 --- a/test-data/typecheck/fields.test +++ b/test-data/typecheck/fields.test @@ -93,4 +93,14 @@ class Abstract(models.Model): abstract = True class User(Abstract): id = models.AutoField(primary_key=True) +[out] + +[CASE standard_it_from_parent_model_could_be_overridden_with_non_integer_field_in_child_model] +from django.db import models +import uuid +class ParentModel(models.Model): + pass +class MyModel(ParentModel): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) +reveal_type(MyModel().id) # E: Revealed type is 'uuid.UUID' [out] \ No newline at end of file