如何使用 Pydantic 将 SQLAlchemy 模型列表序列化为 json?

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

我正在尝试序列化为 SQLAlchemy 模型的 json 或 dict 列表,然后使用 response.json() 对其进行断言:

from datetime import date
from typing import Annotated, Generic, TypeVar

from pydantic import BaseModel, Field

ResultItemSchema = TypeVar("ResultItemSchema", bound=BaseModel)


class TtzSchema(BaseModel):
    id: int
    name: str
    start_date: date


class PaginatedResponseSchema(BaseModel, Generic[ResultItemSchema]):
    count: int
    results: list[ResultItemSchema]


class Ttz(Base):
    __tablename__ = "ttz"

    id: int
    name: str
    start_date: date


cnt = 3
results = [Ttz(...) for i in range(cnt)]

PaginatedResponseSchema[TtzSchema].model_validate({"count": cnt, "results": results})  # does not work. how to serialize to json?

但这不起作用。

sqlalchemy pydantic
1个回答
0
投票

您只需将

model_config = ConfigDict(from_attributes=True) 
添加到您的架构中:

class TtzSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str
    start_date: date

完整代码示例:

from datetime import date, datetime
from typing import Generic, TypeVar

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from pydantic import BaseModel, ConfigDict

class Base(DeclarativeBase):
    pass


ResultItemSchema = TypeVar("ResultItemSchema", bound=BaseModel)


class TtzSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str
    start_date: date


class PaginatedResponseSchema(BaseModel, Generic[ResultItemSchema]):
    count: int
    results: list[ResultItemSchema]


class Ttz(Base):
    __tablename__ = "ttz"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    start_date: Mapped[date]


cnt = 3
results = [Ttz(id=i, name=f"name {i}", start_date=datetime.now().date()) for i in range(cnt)]

res = PaginatedResponseSchema[TtzSchema].model_validate({"count": cnt, "results": results})

print(res)
© www.soinside.com 2019 - 2024. All rights reserved.