简体   繁体   中英

Flexible Schema - BaseModel of Pydantic

I'm using pydantic 1.9.0 and fastapi 0.71.0 with Python 3.7.8. Here's how I've defined my model:

class PartModel(BaseModel):
    _id: str 
    _key: str 
    number: str = Field(...)
    name: str = Field(...)
    price: int = Field(...)

    class Config:
        schema_extra = {
            "example": {
                "_key": "12453",
                "number": "5F22",
                "name": "SHA9-169",
                "price": 4,
            }
        }

I would like to be flexible with the Model because my dictionaries are not consisted when it comes to the length. For example one dictionary might have additional key/value pairs. At the moment when i try to make the request through the FastApi it doesn't allow me to POST in the Database. Is there any way to keep my Model flexible/extendable without defining every key in the class?

In order to work with flexible models, I would recommend to work with Optional fields, as described in https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM