如何在FastAPI的SQLModel中为User表添加Role外键?
在SQLModel中为User添加Role外键关联的实现方法
要实现User表通过role_id关联Role表的外键,你可以按以下方式修改模型:
1. 添加外键字段
直接在User类中定义role_id字段,通过Field的foreign_key参数指定关联的Role表主键,可根据业务需求设置是否允许为空。
2. 可选:添加双向关系(简化ORM操作)
如果需要在查询时直接通过User获取对应Role,或通过Role获取关联的User列表,可添加Relationship字段建立双向关联。
修改后的完整models.py代码:
from typing import Optional, List from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select, Column, VARCHAR class User(SQLModel, table=True): __tablename__ = 'users' user_id: Optional[int] = Field(default=None, primary_key=True) first_name : str = Field(sa_column=Column("first_name", VARCHAR(54),nullable=False)) last_name : str = Field(sa_column=Column("last_name", VARCHAR(54), nullable=True)) email : str = Field(sa_column=Column("email", VARCHAR(54), unique=True, nullable=False)) password : str = Field(sa_column=Column("password", VARCHAR(256), nullable=False)) # 外键字段,关联roles表的role_id role_id: Optional[int] = Field(default=None, foreign_key="roles.role_id") # 双向关联:通过user.role获取对应的Role对象 role: Optional["Role"] = Relationship(back_populates="users") class Role(SQLModel, table=True): __tablename__ = 'roles' role_id: Optional[int] = Field(default=None, primary_key=True) name : str = Field(sa_column=Column("name", VARCHAR(54),nullable=False)) # 双向关联:通过role.users获取所有关联的User列表 users: List["User"] = Relationship(back_populates="role")
关键说明
foreign_key="roles.role_id":格式为表名.字段名,对应Role表的主键role_id。- 若业务要求用户必须绑定角色,可将
role_id的default=None移除,改为nullable=False。 Relationship是可选配置,仅需数据库外键约束时可不添加,但双向关系能大幅简化ORM查询逻辑,比如查询用户时直接加载角色信息。
内容的提问来源于stack exchange,提问作者code_10
相关产品推荐
相关产品推荐

