与SQLAlchemy中的属性指示的映射组的关系

时间:2014-07-25 14:26:46

标签: orm sqlalchemy foreign-key-relationship

我有以下(有点遗留)SQLAlchemy类(在此简化):

class Recipe (Base):
    __tablename__ = 'recipe'

    id = Column(Integer, primary_key=True)
    title = Column(Text)

    ingredients = relationship("Ingredient", order_by="Ingredient.position",
                              backref="recipe", foreign_keys="Ingredient.recipe_id",
                              cascade="all, delete, delete-orphan")

class Ingredient (Base):
    __tablename__ = 'ingredients'

    id = Column(Integer, primary_key=True)
    recipe_id = Column(Integer, ForeignKey('recipe.id'))
    unit = Column(Text)
    amount = Column(Float)
    item = Column(Text)
    inggroup = Column(Text)
    position = Column(Integer)

现在,一种成分可以属于inggroup(想想乳制品,蔬菜等)。

我想修改Recipe.ingredients以产生配方的组合及其中包含的成分的dict(或任何合适的结构),例如{'vegetables': [<Ingredient(2 onions)>, <Ingredient(0.5 kg tomatoes)>], 'spices': <Ingredient(1 pinch salt)>}等。那些群体,我仍然希望按照position字段对成分进行排序。另请注意,一种成分不必属于inggroup - 它可以只是None(在大多数情况下也是如此)。

SQLAlchemy可以吗?

1 个答案:

答案 0 :(得分:0)

我找到了Python itertools.groupby,并将以下hybrid_property添加到Recipe类:

@hybrid_property
def the_ingredients(self):
    return groupby(self.ingredients, lambda x: x.inggroup)