Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Generate Enums for OneOf in OpenAPI Schemas Similar to Enum Fields #2093

Open
REZUCE opened this issue Sep 25, 2024 · 0 comments
Open

Comments

@REZUCE
Copy link

REZUCE commented Sep 25, 2024

Describe the bug

First of all, thank you for the great work on datamodel-code-generator! I have a question regarding how to handle oneOf in OpenAPI schemas, and I'm wondering if it’s possible to generate Python Enums from oneOf, similar to how they are generated from enum fields.

When I use enum in my schema, the generator creates an Enum class as expected, restricting values to the specified enum values. However, when I use oneOf with const values, I would expect similar behavior — an Enum to be generated to enforce these restricted values, but instead, a normal Pydantic model is generated.

To Reproduce
Example schema:

raid:
  type: integer
  enum:
    - 0

When enum is used, it correctly generates the following code:

class DvrRaidLevel(Enum):
    integer_0 = 0

class DvrStorageConfig(BaseModel):
    class Config:
        orm_mode = True
        use_enum_values = True

    raid: Optional[DvrRaidLevel] = Field(None, description="")

But with oneOf:

raid:
  type: integer
  oneOf:
    - title: 0
      const: 0
      description: RAID level 0

It generates:

class DvrRaidLevel(BaseModel):
    class Config:
        orm_mode = True
        use_enum_values = True

    __root__: int

class DvrStorageConfig(BaseModel):
    class Config:
        orm_mode = True
        use_enum_values = True

    raid: Optional[DvrRaidLevel] = Field(None, description="")

Expected behavior
I expect the generator to treat oneOf with const values in a similar way to how it handles enum. Specifically, I would like an Enum to be generated for fields using oneOf to restrict the allowed values. For example, in the case of oneOf, I expect the following code to be generated:

class DvrRaidLevel(Enum):
    integer_0 = 0

class DvrStorageConfig(BaseModel):
    class Config:
        orm_mode = True
        use_enum_values = True

    raid: Optional[DvrRaidLevel] = Field(None, description="")

Version:

  • OS: MacOS
  • Python version: 3.10
  • datamodel-code-generator version: 0.26.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant