如何将组合字段添加到Pydantic模型中

时间:2020-08-19 17:29:49

标签: python fastapi pydantic

说我有模特

class UserDB(BaseModel):
    first_name: Optional[str] = None
    last_name: Optional[str] = None

如何制作由该模型构造的另一个模型,并且该模型的字段会根据此模型中的字段而变化?

例如,类似这样的

class User(BaseModel):
    full_name: str = first_name + ' ' + last_name

也许是这样构造的

User.parse_obj(UserDB)

谢谢!

1 个答案:

答案 0 :(得分:3)

如果您不想将first_namelast_name保留在User中,则可以自定义__init__

否则,您可以使用验证器来设置full_name

两种方法都可以满足您的要求:

from typing import Optional
from pydantic import BaseModel, validator


class UserDB(BaseModel):
    first_name: Optional[str] = None
    last_name: Optional[str] = None


class User_1(BaseModel):
    location: str  # for a change
    full_name: Optional[str] = None

    def __init__(self, user_db: UserDB, **data):
        super().__init__(full_name=f"{user_db.first_name} {user_db.last_name}", **data)


user_db = UserDB(first_name="John", last_name="Stark")
user = User_1(user_db, location="Mars")
print(user)


class User_2(BaseModel):
    first_name: Optional[str] = None
    last_name: Optional[str] = None
    full_name: Optional[str] = None

    @validator('full_name', always=True)
    def ab(cls, v, values) -> str:
        return f"{values['first_name']} {values['last_name']}"


user = User_2(**user_db.dict())
print(user)

输出

location='Mars' full_name='John Stark'
first_name='John' last_name='Stark' full_name='John Stark'

更新: 要使用response_model,您可以通过以下方式自定义__init__

class User_1(BaseModel):
    location: str  # for a change
    full_name: Optional[str] = None

    # def __init__(self, user_db: UserDB, **data):
    def __init__(self, first_name, last_name, **data):
        super().__init__(full_name=f"{first_name} {last_name}", **data)


user_db = UserDB(first_name="John", last_name="Stark")
user = User_1(**user_db.dict(), location="Mars")
print(user)