SQLalchemy表具有来自其他表的多个外键

时间:2018-09-14 01:09:01

标签: python sqlalchemy

我正在尝试学习sqlalchemy,并且对于创建将进入具有对其他两个表的外键的表的对象有点困惑。这是我要尝试做的一个简单示例。我正在制作一个配方数据库,并且具有三个表:recipesingredientsrecipe_ingredientsrecipe_ingredients将成分与配方链接在一起。我有这个积累:

from sqlalchemy import create_engine, Column, Integer, Text, ForeignKey
from sqlalchemy.orm import relationship, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine(u'sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()

class Recipe(Base):
    __tablename__ = 'recipes'
    id = Column(Integer, primary_key=True)
    name = Column(Text)

    recipe_ingredient = relationship('RecipeIngredient', back_populates='recipe')

class Ingredient(Base):
    __tablename__ = 'ingredients'
    id = Column(Integer, primary_key=True)
    name = Column(Text)

    recipe_ingredient = relationship('RecipeIngredient', back_populates='ingredient')

class RecipeIngredient(Base):
    __tablename__ = 'recipe_ingredients'
    id = Column(Integer, primary_key=True)
    recipe_id = Column(Integer, ForeignKey('recipes.id'))
    ingredient_id = Column(Integer, ForeignKey('ingredients.id'))

    recipe = relationship('Recipe', back_populates='recipe_ingredient')
    ingredient = relationship('Ingredient', back_populates='recipe_ingredient')

ham = Ingredient(name='cereal')
bread = Ingredient(name='milk')
cheese = Ingredient(name='cheese')
sandwich = Recipe(name='ham and cheese')
# Now I'm not sure how to link theses
link1 = RecipeIngredient(recipe_id=sandwich.id, ingredient_id=ham.id)
link2 = RecipeIngredient(recipe_id=sandwich.id, ingredient_id=bread.id)
link3 = RecipeIngredient(recipe_id=sandwich.id, ingredient_id=cheese.id)

session.add_all([ham, bread, cheese, sandwich, link1, link2, link3])
session.commit()

由于RecipeIngredient对象,这不起作用。我如何链接这样的外键来创建那些对象?

1 个答案:

答案 0 :(得分:-2)

使用ForeignKeyConstraint和ForeignKey的组合。

    from sqlalchemy import ForeignKeyConstraint

    class RecipeIngredient(Base):
        ...
        recipe_id = Column(Integer, ForeinKey('recipes.id'))
        ingredient_id = Column(Integer)

        __table_args__ = (
        ForeignKeyConstraint(
            ["ingrediants_id"],
            ["ingredients.id"]
        ),)
        ...