I would like to know if it is possible to define with SQLAlchemy the length of an enum type field. In my case the classes are defined as follows:
EnumTest.py
from enum import Enum
class EnumTest(str, Enum):
EnumTest1 = "EnumTest1"
EnumTest2 = "EnumTest2"
EnumTest3 = "EnumTest3"
TestTable.py
from models import Base
from sqlalchemy import Column, Enum, String
from .EnumTest import EnumTest
class TestTable(Base):
__tablename__ = "test"
id = Column(String(50), primary_key=True)
my_enum = Column(Enum(EnumTest), nullable=False)
My goal is to create a field called my_enum of type character varying of length 50 as in the case of the id field.
CodePudding user response:
Docs say
The Enum type will make use of the backend’s native “ENUM” type if one is available; otherwise, it uses a VARCHAR datatype
...
length – allows specifying a custom length for the VARCHAR when Enum.native_enum is False. By default it uses the length of the longest value.
So, you can set native_enum=False
and length=50
. It might look like this
my_enum = Column(Enum(EnumTest, native_enum=False, length=50), nullable=False)