flask sqlalchemy many to many relationship with extra field

前端 未结 2 1923
谎友^
谎友^ 2021-02-18 23:13

I have 2 tables: restaurants and foods, and a 3rd table restaurants_foods which stores the many to many relationship between the 2 tables

restaurants_foods = db.         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-02-18 23:38

    Please take a look at configuring many-to-many relationships in SQLAlchemy. You're going to want something like this:

    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"
        )
    

提交回复
热议问题