烧瓶sqlalchemy许多额外的领域

时间:2016-03-04 12:09:34

标签: flask flask-sqlalchemy

我有2张桌子:餐馆和食物,以及第3张餐馆_食物,它们存储了2张桌子之间的多对多关系

restaurants_foods = db.Table('restaurants_foods',
db.Column('restaurant_id', db.Integer, db.ForeignKey('restaurants.id'), primary_key=True),
db.Column('food_id', db.Integer, db.ForeignKey('foods.id'), primary_key=True),
db.Column('food_price', db.Float))

class Food(Model):
__tablename__ = "foods"

id = db.Column(db.Integer, primary_key=True, autoincrement=True)    
name = db.Column(db.String(255), nullable=False)
description = db.Column(db.String(255), nullable=True)



class Restaurant(Model):
__tablename__ = "restaurants"

id = db.Column(db.Integer, primary_key=True, autoincrement=True)    
name = db.Column(db.String(255), nullable=False)
foods = db.relationship('Food', secondary=restaurants_foods)

现在,当我查询Restautant.query.get(1).foods时,我希望它包含restaurants_foods关联表中的food_price列

2 个答案:

答案 0 :(得分:3)

您必须使用association object模式(是多对多定义的变体):当关联表包含除左,右表外键以外的其他列时,将使用该模式。您可以使用新类直接映射到关联表,而不是使用Relationship.secondary参数。关系的左侧通过一对多引用关联对象,关联类通过多对一引用右侧。下面说明了映射到Association类的关联表,该表包括一列称为extra_data的列,该列是与父级和子级之间的每个关联一起存储的字符串值:

Array

答案 1 :(得分:0)

请查看在SQLAlchemy中配置many-to-many关系。你会想要这样的东西:

restaurants_foods = db.Table('restaurants_foods',
    db.Column('restaurant_id', db.Integer, db.ForeignKey('restaurants.id'), primary_key=True),
    db.Column('food_id', db.Integer, db.ForeignKey('foods.id'), primary_key=True),
    db.Column('food_price', db.Float))


class Food(Model):
    __tablename__ = "foods"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    description = db.Column(db.String(255), nullable=True)
    restaurants = relationship(
        "Restaurant",
        secondary=restaurant_foods,
        back_populates="foods"
    )


class Restaurant(Model):
    __tablename__ = "restaurants"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    foods = relationship(
        "Food",
        secondary=restaurant_foods,
        back_populates="restaurants"
    )