从数据库sqlmodel/fastapi获取树形结构

问题描述 投票:0回答:1

我的数据库中有树形结构 - 评论。

class Comment(SQLModel, table=True):
    id: int = Field(primary_key=True, nullable=False, unique=True)
    text: str = Field(nullable=False)
    parent_id: int = Field(nullable=True, foreign_key="comment.id")
    parent: Optional["Comment"] = Relationship(back_populates="children")
    children: Optional[List["Comment"]] = Relationship(
        back_populates="parent", sa_relationship_kwargs={
            "lazy": "joined", "join_depth": 100, "remote_side": "Comment.id"
        }
    )
class CommentSchema(BaseModel):
    id: int
    text: str
    children: Optional["CommentSchema"] = None
    # children: Optional[List["CommentSchema"]] = []

注释代码返回错误:

'msg':“迭代对象时出错,错误:AttributeError:'Comment'对象没有属性'pydantic_extra'”,

未注释的代码返回列表:

[
  {
    "id": 2 (child id 2),
    "children": {
      "id": 1 (parent id 1),
    }
  },
  {
    "id": 6 (subchild id 6),
    "children": {
      "id": 2 (child id 2),
      "children": {
        "id": 1(parent id 1),
      }
    }
  },
  {
    "id": 5,
    "children": {
      "id": 2 (child id 2),
      "children": {
        "id": 1 (parent id 1),
      }
    }
  },
  {
    "id": 4 (subchild id 4),
    "children": {
      "id": 2 (child 2),
      "children": {
        "id": 1 (parent id 1),
      }
    }
  },
  {
    "id": 3 (subchild id 3),
    "children": {
      "id": 2 (child id 2),
      "children": {
        "id": 1 (parent id 1),
      }
    }
  },
  {
    "id": 1 (parent id 1),
  }
]

我认为我对结果不满意的原因是绝对清楚的。除了编写原始 sql 查询之外,还有什么方法可以从数据库获取正确的树结构?

sqlalchemy fastapi sqlmodel
1个回答
0
投票

首先:

模式.py

class CommentSchema(BaseModel):
    id: int
    text: str
    children: Optional[List["CommentSchema"]] = []

models.py:

class Comment(SQLModel, table=True):
    id: int = Field(primary_key=True, nullable=False, unique=True)
    text: str = Field(nullable=False)
    created: datetime = Field(sa_column=Column(DateTime(timezone=True), server_default=func.now()))
    parent_id: int = Field(nullable=True, foreign_key="comment.id")

    children: Optional[List["Comment"]] = Relationship(
        sa_relationship_kwargs={
            "lazy": "selectin",
            "join_depth": 100,
            "order_by": "Comment.created.desc()",
            "cascade": "delete",
        },
    )

而且有效

© www.soinside.com 2019 - 2024. All rights reserved.