FastAPI 数据库一对一

class Card(Base):
    """银行卡用户基本信息"""
    __tablename__ = 'card'  # 数据库表名

    id = Column(Integer, primary_key=True, autoincrement=True)
    card_id = Column(String(30))
    card_user = Column(String(10))
    tel = Column(String(30))
    card_detail = relationship("CardDetail", uselist=False, backref='card') # uselist 仅一对一False



class CardDetail(Base):
    """银行卡 详情信息"""
    __tablename__ = 'carddetail'  # 数据库表名

    id = Column(Integer, primary_key=True, autoincrement=True)
    mail = Column(String(30))
    city = Column(String(10))
    address = Column(String(30))
    card_id = Column(Integer, ForeignKey('card.id'))
# 查询 card 表,再查询出 carddetail 的数据:

db_card = db.query(Card).filter(Card.id == card.id).first()
card_detail = db_card.card_detail



# 由 carddetail 表,查询 card 表
db_card_detail = db.query(CardDetail).filter(CardDetail.id == card_detail.id).first()
card = db_card_detail.card



# carddetail表增加一条数据和card表进行关联
db_card = db.query(Card).filter(Card.id == card.id).first()

db_card_detail = db.query(CardDetail).filter(CardDetail.id == card_detail.id).first()

db_card.card_detail = db_card_detail
db.add(db_card)
db.commit()
db.refresh(db_card)

Last updated