【发布时间】: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