如何通过SQLModel/FastAPI从数据库获取正确的评论树结构?
解决评论树形结构序列化问题
1. 修正CommentSchema定义
首先要确保Schema的children是列表类型,并且正确配置ORM模式、完成自引用更新:
Pydantic 1.x版本:
class CommentSchema(BaseModel): id: int text: str children: List["CommentSchema"] = [] class Config: orm_mode = True # 必须执行自引用更新,否则序列化时会报错 CommentSchema.update_forward_refs()
Pydantic 2.x版本:
class CommentSchema(BaseModel): id: int text: str children: List["CommentSchema"] = [] model_config = {"from_attributes": True} # 必须执行自引用更新 CommentSchema.update_forward_refs()
2. 手动构建树形结构
直接依赖SQLModel的关联加载可能会出现序列化兼容问题,建议先查询所有评论,再手动构建树:
from sqlmodel import Session, select def get_comment_tree(session: Session): # 查询所有评论,关联加载子节点(依赖模型中配置的lazy="joined") all_comments = session.exec(select(Comment)).all() # 建立评论ID到对象的映射,方便快速查找父节点 comment_map = {comment.id: comment for comment in all_comments} root_comments = [] for comment in all_comments: if comment.parent_id is None: # 根节点直接加入结果列表 root_comments.append(comment) else: # 将当前评论添加到父节点的children列表中 parent_comment = comment_map.get(comment.parent_id) if parent_comment: parent_comment.children.append(comment) # 序列化根节点列表 return CommentSchema.from_orm(root_comments, many=True)
3. 错误原因说明
之前出现AttributeError: 'Comment' object has no attribute '__pydantic_extra__',是因为SQLModel的Relationship返回的是SQLAlchemy的InstrumentedList对象,当Pydantic直接序列化这种特殊列表时,会出现兼容问题。手动构建树形结构后,我们确保children是标准的Python列表,能被Pydantic正确序列化。
内容的提问来源于stack exchange,提问作者Konstantinos
相关产品推荐
相关产品推荐

