2

Let's say I have a generic Food sqlalchemy model that I want to reuse for different apps. In each app, I have a FoodType enum which contains the different types of food I'll use.

I want to be able to pass this app-specific Enum to my generic model. Any idea on how to do that?

Here is my food model:

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

I tried to define an empty enum in my generic model so that it could be overwritten in each app but that apparently doesn't work, it crashes on:

sqlalchemy.exc.StatementError: (builtins.LookupError) "PIZZA" is not among the defined enum values
JPFrancoia
  • 4,866
  • 10
  • 43
  • 73

1 Answers1

1

Make Food a mixin instead of a concrete model, and use declared_attr to define type:

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

Then in your application create the concrete model as:

class Food(FoodMixin, Base):
    food_type = FoodType

Another way would be to define a model factory for Food that takes the enum type as an argument and produces a model:

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

    return Food

and in the app:

Food = food_maker(FoodType, Base)

...Or make the factory return a mixin and inherit from that.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127