ninja-schema icon indicating copy to clipboard operation
ninja-schema copied to clipboard

Fix TextChoices conversion to Enum

Open gabriel-ab opened this issue 9 months ago • 1 comments

Use str as base class in dynamic Enum creation for django Choices

This PR fixes a bug found in django-ninja-extra when using a ModelController and a Model that has a TextChoices in a CharField.

If the Enum is not based on str, the serialization creates the string 'Enum.option' instead of 'option' causing a validation error in pydantic.

gabriel-ab avatar Apr 24 '25 17:04 gabriel-ab

Add Support for IntegerChoices by using the type of the first enum item

This was tested using this model with the ninja-extra ModelController auto schema generation

class User(models.Model):
    class MyKinds(models.TextChoices):
        A = 'a', 'Kind (A)'
        B = 'b', 'Kind (B)'

    class MyColors(models.TextChoices):
        BLUE = 'Blue'
        GREEN = 'Green'

    class MyLevel(models.IntegerChoices):
        L1 = 1
        L2 = 2
        L3 = 3

    name = models.TextField()
    color = models.CharField(max_length=8, choices=MyColors.choices)
    level = models.IntegerField(default=MyLevel.L1, choices=MyLevel.choices)
    kind = models.CharField(default=MyKinds.A, choices=MyKinds.choices)

These are the generated OpenAPI schemas

Enums Created

and the requests work fine.

gabriel-ab avatar Apr 24 '25 22:04 gabriel-ab

@gabriel-ab Awesome. Thanks for fixing this and the test.

eadwinCode avatar Apr 26 '25 06:04 eadwinCode