Skip to content
Advertisement

SQLAlchemy Enum type field with integer value

There is an events model in which I want to add a memebers_count field to indicate the number of participants. The user will make a single selection from the select form. I am using Enum type for this. The model looks like this

JavaScript

An error appears in the console when this entry is made

JavaScript

I assumed the problem was that [e.value for e in obj] should be str instead of int and replaced it with [str(e.value) for e in obj] but got another error

JavaScript

What’s wrong?

Advertisement

Answer

The question is what do you want to persist? two or 2 or <MembersQuantity.two: 2>?

SQLAlchemy docs states:

JavaScript

So if you have integer values of enum, you probably should have something like this:

JavaScript

The name attribute is two, while value attribute is 2 in your case. But you persist only left-hand side strings. You should use values_callable only if you want to persist values instead of names, but docs states also: value_callables - a callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. So you can persist value only if it is a string.

Here is a topic that can be helpful: How to use Enum with SQLAlchemy and Alembic?

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