使用 Python 枚举定义 SQLAlchemy 枚举列会引发“ValueError: not a valid enum"; [英] Defining SQLAlchemy enum column with Python enum raises "ValueError: not a valid enum"

查看:50
本文介绍了使用 Python 枚举定义 SQLAlchemy 枚举列会引发“ValueError: not a valid enum";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照 此示例 在使用Python 的 Enum 类型.我定义了枚举,然后将它传递给列,如示例中所示,但我得到 ValueError: <enum 'FruitType'>不是有效的枚举.如何使用 Python 枚举正确定义 SQLAlchemy 枚举列?

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

推荐答案

列类型应该是 sqlalchemy.types.Enum.您再次使用 Python Enum 类型,它对值有效,但对列类型无效.

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))

这篇关于使用 Python 枚举定义 SQLAlchemy 枚举列会引发“ValueError: not a valid enum";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆