Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Defining SQLAlchemy enum column lenght

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading