tinom9
tinom9

Reputation: 399

Why is mypy not inferring Django CharField choices as type with django-stubs?

I have a Django model with a field that is a models.CharField with choices:

from django.db import models

class MyChoice(models.TextChoices):
    FOO = "foo", _("foo")
    BAR = "bar", _("bar")
    BAZ = "baz", _("baz")

class MyModel(models.Model):
    my_field = models.CharField(choices=MyChoice.choices, max_length=64)

Then, if I use this choice field in a function that has it as a typed parameter, mypy catches it as an error.

def use_choice(choice: MyChoice) -> None:
    pass

def call_use_choice(model: MyModel) -> None:
    use_choice(model.my_field)

# error: Argument 1 to "use_choice" has incompatible type "str"; expected "MyChoice"  [arg-type]

My configuration is as follows:

# pyproject.toml

[tool.poetry.dependencies]
python = ">=3.10,<3.11"
Django = "^3.2.8"

[tool.poetry.dependencies]
mypy = "^1.1.1"
django-stubs = "^1.16.0"
# mypy.ini

[mypy]
python_version = 3.10
ignore_missing_imports = True
plugins =
    mypy_django_plugin.main

[mypy.plugins.django-stubs]
django_settings_module = "config.settings"

Why is this happening?

Upvotes: 3

Views: 1318

Answers (0)

Related Questions