Python 在初始化时为属性转换提供模型的枚举
假设我有一个通用的Python 在初始化时为属性转换提供模型的枚举,python,enums,sqlalchemy,Python,Enums,Sqlalchemy,假设我有一个通用的Foodsqlalchemy模型,我想在几个不同的应用程序中重复使用: class Food(Base): _type = Column(Integer, index=True, unique=False, nullable=False) 这里的\u type属性是一个整数。从技术上讲,它可能是一个枚举,但当我编写通用模型时,我无法访问枚举值(它们稍后在应用程序中定义)。我尝试了Mixin方法(参见我前面的问题:),但我的实际用例比食品示例稍微复杂一些。该模型定义了多
Food
sqlalchemy模型,我想在几个不同的应用程序中重复使用:
class Food(Base):
_type = Column(Integer, index=True, unique=False, nullable=False)
这里的\u type
属性是一个整数。从技术上讲,它可能是一个枚举,但当我编写通用模型时,我无法访问枚举值(它们稍后在应用程序中定义)。我尝试了Mixin方法(参见我前面的问题:),但我的实际用例比食品示例稍微复杂一些。该模型定义了多个关系,其中一个关系指向食品
模型。除其他问题外,这迫使我在应用程序级别声明几个关系,我真的不想这样做
相反,我想这样做:
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
enum,但似乎不可能。我试图覆盖/扩展/子类FoodType
,但尝试失败
你有什么建议吗?好的,我找到的唯一方法是通过给模型/类提供子类(和扩展)枚举来“修补”模型/类:
class FoodType(Enum):
pass
class Food(Base):
food_types: FoodType
_type = Column(Integer, index=True, unique=False, nullable=False)
@hybrid_property
def type(self) -> FoodType:
return self.food_types(self._type)
@type.expression
def type(cls):
return cls._type
@type.setter
def type(self, food_type):
self._type = food_type.value
然后在我的应用程序中,我可以对FoodType进行子类化,添加枚举值,在调用create\u all
之前,我只需要执行以下操作:
Food.Food\u types=MySubClassedEnum