【问题标题】:How to update many to many relationships using SQLAlchemy and FastAPI?如何使用 SQLAlchemy 和 FastAPI 更新多对多关系?
【发布时间】:2022-01-25 00:39:24
【问题描述】:

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")

表“user_roles”中的数据

user_id role_id status
1 1 1
1 2 1
2 1 1

当对 API 的请求对象为 {"user_id":1,"roles":[1,3]} 时,我如何编写 API 来更新 user_roles 表。如何在 FastAPI 中使用 sqlalchemy 来实现这一点?

【问题讨论】:

    标签: python sqlalchemy fastapi


    【解决方案1】:

    首先你应该选择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()
    

    【讨论】:

    • 我的问题是假设如果 user_id=1 具有角色 = [1,2] 并且如果我收到对同一用户的更新请求,我将有效负载作为 {user_id:1,roles: [3]} 现在 orm 必须自动删除 1,2 的记录并添加 role=3 记录。
    • 试试这个。清除角色:user_roles.role = []。然后附加您在有效负载中获得的角色
    猜你喜欢
    • 2021-09-24
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2012-09-17
    • 2012-04-10
    相关资源
    最近更新 更多