【问题标题】:How can I create a backref relationship from sqlalchemy in a pydantic model?如何在 pydantic 模型中从 sqlalchemy 创建反向引用关系?
【发布时间】:2022-08-24 22:07:45
【问题描述】:

我想要一组类别。此类别可以有一个父类别。例子: Music -> Guitars

我有这个 sql 炼金术表:

class Category(Base):
    \"\"\"
    Model of a category
    \"\"\"
    __tablename__ = \"category\"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True, nullable=False)
    color = Column(String, index=True, nullable=True) # Expected to be an HEX string
    description = Column(String, index=True, nullable=True)
    parent_id = Column(Integer, ForeignKey(\"category.id\"), nullable=True)

    parent = relationship(\"Category\", foreign_keys=[parent_id])

所以我创建了以下类:

from typing import Optional
from pydantic import BaseModel


class CategoryBase(BaseModel):
    name: str
    color: str | None = None
    description: str | None = None
    parent_id: int | None = None

class CategoryCreate(CategoryBase):
    pass

class Category(CategoryBase):
    id: int
    parent: Optional[Category] # <--- I want to do something like this

    class Config:
        orm_mode = True

如何让 pydantic 返回类别,例如:

[
  {
    \"name\": \"Guitar\",
    \"color\": \"string\",
    \"parent_id\": 0,
    \"id\": 1,
    \"description\": \"string\",
    \"parent\": {
        \"name\": \"Music\",
        \"color\": \"string\",
        \"parent_id\": null,
        \"parent\": null,
        \"id\": 0,
        \"description\": \"string\"
      }
  },
  {
        \"name\": \"Music\",
        \"color\": \"string\",
        \"parent_id\": null,
        \"parent\", null,
        \"id\": 0,
        \"description\": \"string\"
      }
 ]

有没有办法在 pydantic 中定义可选的“自我类”?

    标签: python sqlalchemy pydantic


    【解决方案1】:

    我也有同样的问题。你解决了吗?

    【讨论】:

    猜你喜欢
    • 2014-12-28
    • 2021-06-04
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2020-05-12
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多