Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

flask - Defining SQLAlchemy enum column with Python enum raises "ValueError: not a valid enum"

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
question from:https://stackoverflow.com/questions/36136112/defining-sqlalchemy-enum-column-with-python-enum-raises-valueerror-not-a-valid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The column type should be sqlalchemy.types.Enum. You're using the Python Enum type again, which is valid for the value but not the column type.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...