【问题标题】:Provide an enum to model at init time for attribute conversion在初始化时为模型提供枚举以进行属性转换
【发布时间】: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


    【解决方案1】:

    好的,我发现的唯一方法是通过为模型/类提供子类(和扩展)枚举来“猴子补丁”模型/类:

    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_all 之前我只需要这样做:

    Food.food_types = MySubClassedEnum

    【讨论】:

      猜你喜欢
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      相关资源
      最近更新 更多