【发布时间】:2019-11-04 13:12:39
【问题描述】:
假设我有一个通用的Food sqlalchemy 模型,我想在几个不同的应用程序中重复使用它:
class Food(Base):
_type = Column(Integer, index=True, unique=False, nullable=False)
这里的_type 属性是一个整数。从技术上讲,它可能是一个枚举,但是当我编写我的通用模型时,我无法访问枚举值(它们稍后在应用程序中定义)。我尝试了 Mixin 方法(请参阅我之前的问题:provide Enum at DB creation time),但我的实际用例比Food 示例稍微复杂一些。此模型上定义了多个关系,包括一个指向 Food 模型的关系。除其他问题外,这迫使我在应用级别声明多个关系,我真的不想这样做。
相反,我想做这样的事情:
class FoodType(Enum):
pass
class Food(Base):
_type = Column(Integer, index=True, unique=False, nullable=False)
@hybrid_property
def type(self) -> FoodType:
return FoodType(self._type)
@type.setter
def type(self, food_type):
self._type = food_type.value
我想稍后在应用程序级别以某种方式“填充”FoodType 枚举,但这似乎是不可能的。我试图覆盖/扩展/子类FoodType,但我的尝试没有成功。
你有什么建议吗?
【问题讨论】:
标签: python enums sqlalchemy