使用带枚举类型列的python / sqlalchemy创建表

时间:2018-02-22 16:18:30

标签: python enums sqlalchemy

错误来自以下代码的第16行('gender = db.Column(db.Enum(Gender),nullable = False)'。

from flask_sqlalchemy import SQLAlchemy
from .views import app
import enum

db = SQLAlchemy(app)

class Gender(enum.Enum):
    female = 0
    male = 1
    other = 2

class Content(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200), nullable=False)
    gender = db.Column(db.Enum(Gender), nullable=False)

    def __init__(self, description, gender):
        self.description = description
        self.gender = gender


def init_db():
    db.drop_all()
    db.create_all()
    db.session.add(Content("THIS IS SPARTAAAAAAA!!!", Gender['male']))
    db.session.add(Content("What's your favorite scary movie?", 
Gender['female']))
    db.session.commit()
    lg.warning('Database initialized!')

我得到了这个错误堆栈跟踪

Traceback (most recent call last):
  File "run.py", line 3, in <module>
    from fbapp import app
  File "__init__.py", line 5, in <module>
    from . import models
  File "models.py", line 13, in <module>
    class Content(db.Model):
  File "models.py", line 16, in Content
    gender = db.Column(db.Enum(Gender), nullable=False)
  File "sqltypes.py", line 1296, in __init__
    self._enum_init(enums, kw)
  File "sqltypes.py", line 1332, in _enum_init
    length = max(len(x) for x in self.enums)
  File "sqltypes.py", line 1332, in <genexpr>
    length = max(len(x) for x in self.enums)
TypeError: object of type 'type' has no len()

有人能告诉我我的错误在哪里吗?感谢。

0 个答案:

没有答案