How to keep VARCHAR in the DB (MYSQL), but ENUM in the sqlalchemy model

Question:

I want to add a new Int column to my MYSQL DB, so that in the sqlalchemy ORM it will be converted to an ENUM.

For example, let’s say I have this enum:

class employee_type(Enum):
    Full_time = 1
    Part_time = 2
    Student = 3

I want to keep in the DB those params – 1,2,3..., but when developers will write code that involves this model – they will just use the Enum, without having to go through getter and setter functions.

So they will be able to do – instance_of_model.employee_type and get an Enum. And – new_instance = model_name(employee_type=Employee_type.Full_time..)

How should I define my sqlalchemy model so it will work? (I’ve heard of hybrid types but not sure it will work here)

Thanks!

Asked By: lmaayanl

||

Answers:

Apparently the answer is super simple(!), there is nothing special we need to do – SQLAlchemy support it by itself.

Meaning – you can set the specific column to be INT in the DB, but enum in the model, and when querying the DB SQLAlchemy will convert it by itself. same goes when inserting to the DB 🙂

I used it with declarative enum, it means it’s values are strings (and it has a function – from_string()).
So once I used VARCHAR columns, it worked like a charm!

Answered By: lmaayanl

Sqlalchemy checks the db if native type enum is available.

If the db does not support this, the default type is VARCHAR.

So you can

Enum(MyEnum, native_enum=False)
Answered By: Hyung Doe
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.