如何使用SQLAlChemy和FastAPI更新多对多关系? [英] How to update many to many relationships using SQLAlchemy and FastAPI?

查看:0
本文介绍了如何使用SQLAlChemy和FastAPI更新多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Models.py

class Role(Base):
    __tablename__='role'
    role_id = Column(Integer,primary_key=True)
    role_name = Column(String(20),nullable=False)

class User(Base):
    __tablename__='user'
    user_id = Column(Integer,primary_key=True)
    user_name = Column(String(20),nullable=False)

class UserRoles(Base):
    __tablename__="user_roles"
    user_id = Column(Integer,ForeignKey("User.user_id"),primary_key=True)
    role_id = Column(Integer,ForeignKey("Role.role_id"),primary_key=True)
    status = Column(Integer,nullable=True)
    user = relationship("User")
    role = relationship("role")

表中的数据

用户ID 角色ID 状态
1 1 1
1 2 1
2 1 1

当接口的请求对象为{";user_id";:1,";Roles";:[1,3]}时,如何编写更新user_Roles表的接口。如何在FastAPI中使用SQLalChemy实现此目的?

推荐答案

首先应选择UserRoles进行更新:

results = await session.execute(
    select(UserRoles).where(UserRoles.id == user_id)
)  # where user_id = 1
user_roles = results.scalars().all()[0]

获得一个角色可能有更简单的方法,您应该看看docs

然后选择要追加到ManyToMany字段的全部Roles

roles = await session.execute(select(Role).where(Role.role_id.in_(roles)))  # Where roles = [1, 3]

然后将它们添加到列表中:

for role in roles.scalars().all():
    user_roles.role.append(role)

和提交会话:

await session.commit()

这篇关于如何使用SQLAlChemy和FastAPI更新多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆