如何向Flask-SQLAlchemy中db.Table定义的tags表添加记录?
如何向Flask-SQLAlchemy的db.Table关联表中添加记录?
你当前使用Flask+Flask-SQLAlchemy开发,数据库为本地SQLite,配置及模型定义如下:
数据库配置:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///manage.db'
模型类:
class House(db.Model): __tablename__ = 'house' id: Mapped[int] = mapped_column(db.Integer, primary_key=True) block: Mapped[str] = mapped_column(db.String, nullable=False) number: Mapped[str] = mapped_column(db.String, nullable=False) area: Mapped[int] = mapped_column(db.Integer) class Residents(db.Model): __tablename__ = 'residents' r_id: Mapped[str] = mapped_column(db.String, primary_key=True) r_name: Mapped[str] = mapped_column(db.String) r_phone: Mapped[str] = mapped_column(db.String, nullable=False) r_work_place: Mapped[str] = mapped_column(db.String, nullable=False)
关联表定义:
tags = db.Table('tags', db.Column('house_id',db.Integer, db.ForeignKey('house.id')), db.Column('res_id',db.String, db.ForeignKey('residents.r_id')) )
方法一:通过ORM关联关系添加(推荐)
首先在两个模型中定义多对多关联,这样可以直接通过模型实例操作关联关系,更符合ORM的设计思路:
修改House和Residents模型,添加关联字段:
class House(db.Model): __tablename__ = 'house' id: Mapped[int] = mapped_column(db.Integer, primary_key=True) block: Mapped[str] = mapped_column(db.String, nullable=False) number: Mapped[str] = mapped_column(db.String, nullable=False) area: Mapped[int] = mapped_column(db.Integer) # 添加与住户的多对多关联 residents = db.relationship('Residents', secondary=tags, backref=db.backref('houses', lazy='dynamic')) class Residents(db.Model): __tablename__ = 'residents' r_id: Mapped[str] = mapped_column(db.String, primary_key=True) r_name: Mapped[str] = mapped_column(db.String) r_phone: Mapped[str] = mapped_column(db.String, nullable=False) r_work_place: Mapped[str] = mapped_column(db.String, nullable=False)
之后就可以通过模型实例直接添加关联记录:
# 先获取已存在的房屋和住户实例 house = House.query.get(1) # 假设id为1的房屋存在 resident = Residents.query.get('R001') # 假设r_id为R001的住户存在 # 添加关联 house.residents.append(resident) # 提交到数据库 db.session.commit()
若要移除关联,使用remove方法:
house.residents.remove(resident) db.session.commit()
方法二:直接操作关联表(仅特殊场景使用)
如果不想定义模型关联,也可以直接向tags表插入数据:
# 插入一条关联记录 db.session.execute(tags.insert().values(house_id=1, res_id='R001')) db.session.commit()
注意:这种方式需要手动确保house_id和res_id对应的记录在各自表中存在,否则会触发外键约束错误。
内容的提问来源于stack exchange,提问作者pyhappyer
相关产品推荐
相关产品推荐

