这是sqlalchemy中枚举最佳方法的有趣答案的后续。Cito将Zzzeeks的答案扩展到包括订购,这非常好。Cito还在结尾处留下了一段诱人的代码。
class DeclEnumType(SchemaType, TypeDecorator):
"""DeclEnum augmented so that it can persist to the database."""
这正是我试图构建的Python枚举,它在数据库中自己的表中表示。其中EmployeeType.full_time在Python代码中可用,并且在DB中有自己的表(对于这个简单的示例,只有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))
关于如何获得这种双重代表性,有什么想法吗?
如果我没有错的话,做:
type = Column(EmployeeType.db_type())
而不是
type = Column(DeclEnumType(EmployeeType))
应该这样做。