Skip to content
Advertisement

Pydantic/SQLAlchemy: How to work with enums?

What is the best way to convert a sqlalchemy model to a pydantic schema (model) if it includes an enum field?

Sqlalchemy

JavaScript

Pydantic

JavaScript

Conversion

JavaScript

This leads to the error

value is not a valid enumeration member; permitted: 'CREATED', 'UPDATED' (type=type_error.enum; enum_values=[<StateEnumDTO.CREATED: 'CREATED'>, <StateEnumDTO.UPDATED: 'UPDATED'>])

How can I configure either

a.) the serialization with the from_orm method?

or

b.) the creation of the state field?

c.) How to convert it the other way around?

Is there a native way to do this with pydantic or how is this typically done?

Update: Test case

JavaScript

Advertisement

Answer

Pydantic requires that both enum classes have the same type definition.

In your case, StateEnum inherits from enum.Enum, but StateEnumDTO inherits from both str and enum.Enum.

You can fix this issue by changing your SQLAlchemy enum definition:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement