Skip to main content
 首页 » 编程设计

python之在数据库创建时提供枚举

2024年11月01日8findumars

假设我有一个通用的 Food sqlalchemy 模型,我想将其重用于不同的应用程序。 在每个应用程序中,我都有一个 FoodType 枚举,其中包含我将使用的不同类型的食物。

我希望能够将这个特定于应用程序的 Enum 传递给我的通用模型。知道如何做到这一点吗?

这是我的食物模型:

class Food(Base): 
    type = Column(Enum(FoodType, name="l=food_type")) 

我试图在我的通用模型中定义一个空枚举,以便它可以在每个应用程序中被覆盖,但这显然不起作用,它崩溃了:

sqlalchemy.exc.StatementError: (builtins.LookupError) "PIZZA" is not among the defined enum values 

请您参考如下方法:

将 Food 设为 mixin而不是具体模型,并使用 declared_attr定义类型:

class FoodMixin: 
    @declared_attr 
    def type(cls): 
        return Column(Enum(cls.food_type, name="food_type")) 

然后在您的应用程序中创建具体模型:

class Food(FoodMixin, Base): 
    food_type = FoodType 

另一种方法是为 Food 定义一个模型工厂,它将枚举类型作为参数并生成一个模型:

def food_maker(FoodType, Base): 
    class Food(Base): 
        type = Column(Enum(FoodType, name="food_type")) 
 
    return Food 

在应用程序中:

Food = food_maker(FoodType, Base) 

...或者让工厂返回一个 mixin 并从中继承。