model - 使用 pydantic 模型将不同 fastapi 模型的公共(public)字段集中在一个地方

标签 model fastapi pydantic

我正在使用 fastapi 框架并使用 Pydantic 创建模型。我有 2 个模型 customerProfileShort 和 CustomerProfileLong 。这些模型中有 6 个字段是常见的。是否有一种方法可以在一个地方定义文件并在任何地方重用它们模型。

像这样在一个地方定义它们

地址:可选[str] = 字段(example="4849 William Terrace")

在不同的模型中使用相同的内容

我必须这样做?或者任何更简单的方法??

class First_name(BaseModel):
    first_name: str = Field(None, example="John")
class Last_name(BaseModel):
    last_name: str = Field(None, example="Doe")
class Actions_Count(BaseModel):
    actions_count: int = Field(None, example=131)
class Event_performed(BaseModel)
    action_name: str Field(None, example="check out")
class Address(BaseModel):
    address: Optional[str] = Field(example="4849 William Terrace")
class State(BaseModel):
    state: Optional[str] = Field(example="NC")
class Country(BaseModel):
    country: Optional[str] = Field(example="US")
    
class ShortCustomerProfile(Address,Actions_Count,Last_name,First_name):
        pass

Class State_Counts(State,Country):
        pass

class Events_Performed_By_Customer(First_name,Last_name,Event_performed):
        pass

我正在使用 fastapi 框架并使用 Pydantic 创建模型。我有 2 个模型 customerProfileShort 和 CustomerProfileLong 。这些模型中有 6 个字段是常见的。是否有一种方法可以在一个地方定义文件并在任何地方重用它们模型。

像这样在一个地方定义它们

地址:可选[str] = 字段(example="4849 William Terrace")

在不同的模型中使用相同的内容

最佳答案

Pydantic 支持继承,就像任何其他 Python 类一样。也是given as an example in the FastAPI docs 。您可以通过创建一个基础模型来实现此目的,然后从中继承(您可以根据需要在任意多个层中执行此操作,但要小心不要使代码难以理解)。

class CustomerProfileShort:
    address: Optional[str] = Field(example="4849 William Terrace")


class CustomerProfileLong(CustomerProfileShort):
    more_information: str

Python 还支持多重继承,因此您可以根据许多其他较小的模型应支持的内容“组合”结果模型。但再次强调,请注意不要过度使用,因为这只会使您的代码更难以遵循和理解。

关于model - 使用 pydantic 模型将不同 fastapi 模型的公共(public)字段集中在一个地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73647450/

相关文章:

python - Django:如何创建一个包含另一个模型的所有字段(但与之无关)的新模型?

python 无法使用 HTTP 请求从异步函数获取返回值

python - 如何解析一个pydantic模型中的ObjectId?

logging - FastAPI uvicorn 不记录错误

python - Pydantic:使用不同编码导出相同类型的字段

python - 在 Post 请求正文中发送列表值以验证 Pydantic 模型

php - 如何在 Laravel 5.4 中的 firstOrCreate 中使用 where

python - 在管理中预填充 django 水平过滤器

r - 具有自回归项的 GLM 以校正序列相关性

python - 使用 FastAPI 计算全局变量的请求数