47

I am trying to follow this example to have an enum column in a table that uses Python's Enum type. I define the enum then pass it to the column as shown in the example, but I get ValueError: <enum 'FruitType'> is not a valid Enum. How do I correctly define a SQLAlchemy enum column with a Python enum?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import enum

app = Flask(__name__)
db = SQLAlchemy(app)

class FruitType(enum.Enum):
    APPLE = "Crunchy apple"
    BANANA = "Sweet banana"

class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    fruit_type = db.Column(enum.Enum(FruitType))
File "why.py", line 32, in <module>
    class MyTable(db.Model):
  File "why.py", line 34, in MyTable
    fruit_type = db.Column(enum.Enum(FruitType))
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 330, in __call__
    return cls.__new__(cls, value)
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 642, in __new__
    raise ValueError("%s is not a valid %s" % (value, cls.__name__))
ValueError: <enum 'FruitType'> is not a valid Enum

2 Answers 2

87

The column type should be sqlalchemy.types.Enum. You're using the Python Enum type again, which was valid for the value but not the column type. Back in 2016, when the question was written, this was necessary:

class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    fruit_type = db.Column(db.Enum(FruitType))

However, this is not the case anymore.

Sign up to request clarification or add additional context in comments.

6 Comments

It raises: TypeError: object of type 'type' has no len()
@AmirShabani did you ever figure this out?
@Chris I use flask sqlalchemy like this: db.Column(db.Enum("AutoService", "Insurance", "CarWash", name="service_category"))
@AmirShabani thanks, thats what i ended up doing, just unfortunate that you have to maintain it in two different locations if you want a class enum to be used elsewhere in your code
@AmirShabani @Chris Please note that although the column type should be sqlalchemy.types.Enum, the class which represent the enum should inherit from Python's enum.Enum - (Enum or enum34) - you can see the example
|
0

You are using enum.Enum() directly in the database column.however this is not right Because enum.Enum isn’t a SQL column type — it's just the base for your Python enum. So passing it directly in db.Column() won’t correctly register the ENUM type with SQLAlchemy or your DB.

corrected line:

fruit_type = db.Column(Enum(FruitType))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.