SQLAlchemy枚举代码表示_和_数据库表示

时间:2013-02-22 21:07:06

标签: python sqlalchemy

这是对best-way-to-do-enum-in-sqlalchemy非常有趣的答案的跟进。 Cito扩展了Zzzeeks的答案,包括非常好的订购。 Cito还在最后附近留下了一些诱人的代码。

class DeclEnumType(SchemaType, TypeDecorator):
    """DeclEnum augmented so that it can persist to the database."""

这正是我试图建立的Python枚举,它在db中自己的表中表示。 EmployeeType.full_time在Python代码中可用的地方在数据库中有自己的表(对于这个简单的例子,只是一个idx和名称)。

但是,我不确定我是否理解如何使用Cito的DeclEnumType示例,因为以下内容未在数据库中创建EmployeeType表。

class EmployeeType(DeclEnum):
    # order will be as stated: full_time, part_time, contractor
    full_time = EnumSymbol("Full Time")
    part_time = EnumSymbol("Part Time")
    contractor = EnumSymbol("Contractor")

class Employee(Base):
    __tablename__ = 'employee'

    id = Column(Integer, primary_key=True)
    name = Column(String(60), nullable=False)
    type = Column(DeclEnumType(EmployeeType))

关于如何获得这种双重表示的任何想法?

1 个答案:

答案 0 :(得分:1)

如果我没弄错的话,做:

type = Column(EmployeeType.db_type())

而不是

type = Column(DeclEnumType(EmployeeType))

应该这样做。

相关问题