I am trying to return my model with the defined field names instead of its aliases.
class FooModel(BaseModel):
foo: str = Field(..., alias="bar")
@app.get("/") -> FooModel:
return FooModel(**{"bar": "baz"})
The response will be {"bar": "baz"}
while I want {"foo": "baz"}
. I know it's somewhat possible when using the dict
method of the model, but it doesn't feel right and messes up the typing of the request handler.
@app.get("/") -> FooModel:
return FooModel(**{"bar": "baz"}).dict(by_alias=False)
I feel like it should be possible to set this in the config class , but I can't find the right option.
You can add response_model_by_alias=False
to path operation decorator. This key is mentioned here in the documentation.
For example:
@app.get("/model", response_model=Model, response_model_by_alias=False)
def read_model():
return Model(alias="Foo")
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.