【问题标题】:With fastapi/SQLModel, how to specify the order the columns/fields are shown in a table/response object?使用 fastapi/SQLModel,如何指定列/字段在表/响应对象中的显示顺序?
【发布时间】:2021-12-31 09:44:12
【问题描述】:

我有以下模型/模式:

class UserBase(SQLModel):
    full_name: str
    email: EmailStr
    is_active: bool = True
    is_superuser: bool = False


class UserRead(UserBase):
    id: uuid.UUID


class UserCreate(UserBase, extra=Extra.forbid):
    password: str


class UserUpdate(UserBase):
    password: Optional[str] = None


class User(UserBase, table=True):
    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True,
        index=True,
        nullable=False,
    )
    hashed_password: Optional[str] = None

在我的 postgres 客户端中,表格按字段在模型/模式中列出的顺序显示列:

此外,openapi 文档按照User 模型中指定的相同顺序列出了响应对象字段(请注意图像底部的响应对象):

我想让id 成为表格/响应对象中显示的第一列/字段。一般而言,如何强制执行列/字段的特定顺序?

【问题讨论】:

  • 不同的 json 客户端和配置会显示不同的顺序,所以没有必要这样做,json 客户端不关心数据顺序
  • 我明白了,感谢您的评论。关于表格列的顺序,我们能做些什么吗?

标签: python fastapi sqlmodel


【解决方案1】:

正如 cmets 中所讨论的,没有必要对 json 输出进行排序,因为 json 客户端不关心数据顺序。

关于你的 sql db 中的数据顺序,你可以对其进行排序,这只是模型继承的问题(它也会导致我们之前讨论的 json 顺序)

您应该遵循一些关于您将哪些数据放入数据库中的规则。

在经典 sql 表中,您将第一列作为 ID,用于生成它们的模型应与此结构匹配。

由于 ID 是所有用户都将拥有的数据,因此它应该在您的基本模型中,因此相同的规则适用于您的所有基本用户数据。

我会做什么(folowing the exemple from the lib):

class UserBase(SQLModel, table=True):
    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True,
        index=True,
        nullable=False,
    )
    hashed_password: Optional[str] = None
    full_name: str
    email: EmailStr
    is_active: bool = True
    is_superuser: bool = False

这样,您就可以创建其他派生自它的类。 (如有必要)

【讨论】:

  • 我知道你的意思,但这不是一个 DRY 解决方案,它会导致不必要的代码复制。此外,您链接到的示例只是一个玩具示例,它不会受益于继承来指定用于读取、创建等的不同模式。例如,对 GET 的响应不应返回 idhashed_password
猜你喜欢
  • 2022-01-07
  • 2023-02-07
  • 1970-01-01
  • 2020-07-23
  • 2022-11-15
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多