46

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
davidism
  • 121,510
  • 29
  • 395
  • 339
Digital
  • 643
  • 2
  • 8
  • 12

1 Answers1

85

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.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
r-m-n
  • 14,192
  • 4
  • 69
  • 68
  • 3
    It raises: TypeError: object of type 'type' has no len() – Amir Shabani May 08 '18 at 05:39
  • 1
    @AmirShabani did you ever figure this out? – Chris Aug 22 '18 at 18:41
  • 1
    @Chris I use flask sqlalchemy like this: db.Column(db.Enum("AutoService", "Insurance", "CarWash", name="service_category")) – Amir Shabani Aug 22 '18 at 18:55
  • 2
    @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 – Chris Aug 23 '18 at 19:11
  • 3
    @AmirShabani @Chris Please note that although the column type should be [`sqlalchemy.types.Enum`](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Enum), the class which represent the enum should inherit from Python's `enum.Enum` - ([Enum](https://docs.python.org/3/library/enum.html) or [enum34](https://pypi.org/project/enum34/)) - you can see the [example](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Enum) – Israel N Aug 28 '18 at 12:58
  • FYI - This causes errors in Flask Admin, I ended up using this solution: https://stackoverflow.com/a/33042283/50348 – Nick Woodhams Apr 23 '19 at 07:01