我正在使用flask做一个项目,我选择Flask-sqlalchemy来存储数据。数据库存储在本地:
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`your text`.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'))
)
现在我想向表'tags'添加记录,该表定义为db.Table,如何实现这个过程?
如果您按照文档中所述为双向多对多关系添加映射,则可以像在列表中一样添加和删除对象。
from sqlalchemy.orm import (
Mapped,
relationship
)
from typing import List
class House(db.Model):
# ...
residents: Mapped[List['Residents']] = relationship(
secondary=tags, back_populates='houses'
)
class Residents(db.Model):
# ...
houses: Mapped[List['House']] = relationship(
secondary=tags, back_populates='residents'
)
house = House(...)
db.session.add(house)
db.session.commit()
resident = Residents(...)
house.residents.append(resident)
db.session.commit()