3

Assume a REST API which defines a POST method on a resource /foos to create a new Foo. When creating a Foo the name of the Foo is an input parameter (present in the request body). When the server creates a Foo it assigns it an ID. This ID is returned together with the name in the REST response. I am looking for something similar to readOnly in OpenAPI.

The input JSON should look like this:

{
    "name": "bar"
}

The output JSON should look like that:

{
    "id": 123,
    "name": "bar"
}

Is there a way to reuse the same pydantic model? Or is it necessary to use two diffent models?

class FooIn(BaseModel):
    name: str

class Foo(BaseModel):
    id: int
    name: str

I cannot find any mentions of "read only", "read-only", or "readonly" in the pydantic documentation or in the Field class code.

Googling I found a post which mentions

id: int = Schema(..., readonly=True)

But that seems to have no effect in my use case.

4

1 回答 1

3

有多个模型很好。您可以使用继承来减少代码重复:

from pydantic import BaseModel


# Properties to receive via API create/update
class Foo(BaseModel):
    name: str


# Properties to return via API
class FooDB(Foo):
    id: int

顺便说一句,文档 很棒!, 对此进行了更深入的探讨。

是一个真实的用户模型示例,取自官方的全栈项目生成器。您可以看到有多个模型如何根据上下文定义用户模式。

于 2020-01-27T20:31:39.817 回答