ninja-schema
ninja-schema copied to clipboard
Fix TextChoices conversion to Enum
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.
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
and the requests work fine.
@gabriel-ab Awesome. Thanks for fixing this and the test.