python - 带额外字段的 flask sqlalchemy多对多

标签 python flask sqlalchemy flask-sqlalchemy

我有2个表:餐厅和食物,还有第3个表Restaurants_foods,用于存储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列

最佳答案

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

class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child", back_populates="parents")
    parent = relationship("Parent", back_populates="children")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association", back_populates="parent")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship("Association", back_populates="child")

关于python - 带额外字段的 flask sqlalchemy多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35795717/

相关文章:

python - Flask Sqlalchemy中如何分离主从(DB读/写)

python - 在 sqlalchemy 中选择

python - 为 MS-SQL 创建不区分大小写的 SQLAlchemy 查询

mysql - SQL:使用类似列表的数据在 col 中搜索匹配元素的有效方法

python - pytorch.empty 函数中未初始化的数据是什么

python - 将多索引数据帧的子集除以字典中的值

python - 提交后如何将字段值保留在表单中?

python - 在不使用内置函数的情况下返回第 n 个最小的数字 - Python

python - 如何在 Python 中解栈嵌套元组?

python - 类型错误 : <Response 36 bytes [200 OK]> is not JSON serializable