Skip to content

Custom fields with overwritten passthrough constructors don't change types based on attributes #2043

Open
@md384

Description

@md384

Bug report

What's wrong

When creating a custom model field with a constructor that uses *args, **kwargs to pass arguments to the parent constructor, attributes that change the typing of the field are not considered.

Below is a simple example where my_custom_field has null=True kwarg so the type of the field on the model instance should be Union[builtins.int, None] but is incorrectly builtins.int.

-   case: test_custom_model_fields
    main: |
        from myapp.models import User
        user = User()
        reveal_type(user.id)  # N: Revealed type is "builtins.int"
        reveal_type(user.my_custom_field)  # N: Revealed type is "Union[builtins.int, None]"
    monkeypatch: true
    installed_apps:
        - myapp
    files:
        -   path: myapp/__init__.py
        -   path: myapp/models.py
            content: |
                from django.db import models
                from django.db.models import fields

                from typing import Any, TypeVar

                _ST = TypeVar("_ST", contravariant=True)
                _GT = TypeVar("_GT", covariant=True)

                class MyIntegerField(fields.IntegerField[_ST, _GT]):
                    def __init__(self, *args: Any, **kwargs: Any) -> None:
                        super().__init__(*args, **kwargs)

                class User(models.Model):
                    id = models.AutoField(primary_key=True)
                    my_custom_field = MyIntegerField(null=True)

How is that should be

reveal_type(user.my_custom_field) # N: Revealed type is "Union[builtins.int, None]"

System information

  • OS:
  • python version: 3.11
  • django version: 4.2.5
  • mypy version: 1.7.1
  • django-stubs version: 4.2.7
  • django-stubs-ext version: 4.2.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions