Fix Python – Best way to do enum in Sqlalchemy?


Asked By – Timmy

I’m reading about sqlalchemy and I saw following code:

employees_table = Table('employees', metadata,
    Column('employee_id', Integer, primary_key=True),
    Column('name', String(50)),
    Column('manager_data', String(50)),
    Column('engineer_info', String(50)),
    Column('type', String(20), nullable=False)

employee_mapper = mapper(Employee, employees_table, \
    polymorphic_on=employees_table.c.type, polymorphic_identity='employee')
manager_mapper = mapper(Manager, inherits=employee_mapper, polymorphic_identity='manager')
engineer_mapper = mapper(Engineer, inherits=employee_mapper, polymorphic_identity='engineer')

Should I make ‘type’ an int, with constants in a library? Or should I make just make type an enum?

Now we will see solution for issue: Best way to do enum in Sqlalchemy?


SQLAlchemy has an Enum type since 0.6:

Although I would only recommend its usage if your database has a native enum type. Otherwise I would personally just use an int.

This question is answered By – Wolph

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0