我正在尝试按照this example在包含Python Enum
类型的表中使用枚举列。我定义了枚举,然后将其传递给列,如示例所示,但我得到ValueError: <enum 'FruitType'> is not a valid Enum
。如何使用Python枚举正确定义SQLAlchemy枚举列?
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
答案 0 :(得分:47)
列类型应为sqlalchemy.types.Enum
。您再次使用Python Enum
类型,它对值有效,但对列类型无效。
class MyTable(db.Model):
id = db.Column(db.Integer, primary_key = True)
fruit_type = db.Column(db.Enum(FruitType))