pydantic_model_creator is not generating tortoise.field.CharEnumField as enumeration
See original GitHub issueDescribe the bug
I am currently using the method pydantic_model_creator
from tortoise.contrib.pydantic
to generate my pydantic model from my tortoise model.
However, the generation is not behaving as I would expect it to be for the tortoise field CharEnumField
. The pydantic model generated from a tortoise model containing a CharEnumField
is set as a Char field and not an Enum field.
The OpenApi schema generated is:
"my_enum": {
"title": "My Enum",
"description": "A: a<br/>B: b<br/>C: c",
"maxLength": 1,
"type": "string"
}
The OpenApi schema generated from a pydantic mode (that is not created from a tortoise model) results in the following:
"MyEnum": {
"title": "MyEnum",
"description": "An enumeration.",
"enum": [
"a",
"b",
"c"
],
"type": "string"
}
To Reproduce
from enum import Enum
from pydantic import BaseModel
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model
class MyEnum(str, Enum):
A = "a"
B = "b"
C = "c"
class MyModel(Model):
my_enum = fields.CharEnumField(MyEnum)
class MyModelPydantic(BaseModel):
my_enum: MyEnum
MyModelPydanticCreator = pydantic_model_creator(MyModel, name="MyModelPydanticCreator")
print(MyModelPydanticCreator.schema_json(indent=2))
# Output :
# {
# "title": "MyModelPydanticCreator",
# "type": "object",
# "properties": {
# "id": {
# "title": "Id",
# "minimum": 1,
# "maximum": 2147483647,
# "type": "integer"
# },
# "my_enum": {
# "title": "My Enum",
# "description": "A: a<br/>B: b<br/>C: c",
# "maxLength": 1,
# "type": "string"
# }
# },
# "required": [
# "id",
# "my_enum"
# ],
# "additionalProperties": false
# }
print(MyModelPydantic.schema_json(indent=2))
# Output :
# {
# "title": "MyModelPydantic",
# "type": "object",
# "properties": {
# "my_enum": {
# "$ref": "#/definitions/MyEnum"
# }
# },
# "required": [
# "my_enum"
# ],
# "definitions": {
# "MyEnum": {
# "title": "MyEnum",
# "description": "An enumeration.",
# "enum": [
# "a",
# "b",
# "c"
# ],
# "type": "string"
# }
# }
# }
Expected behaviour I would expect that both ways of creating the pydantic model result in the same OpenApi schema/Pydantic model, i.e. using an enum field and not a basic char field.
Additional context I am using FastApi / Tortoise-Orm / Pydantic. I came across this problem because my pydantic model (which is the body requested by my FastApi endpoint) was letting strings that are not in my enum through the endpoint entry.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:5
Looking for the same solution
I have same problem. Any update?