我试图用定义的字段名称而不是别名返回我的模型。
class FooModel(BaseModel):
foo: str = Field(..., alias="bar")
@app.get("/") -> FooModel:
return FooModel(**{"bar": "baz"})
Run Code Online (Sandbox Code Playgroud)
{"bar": "baz"}当我想要的时候就会得到回应{"foo": "baz"}。我知道使用dict模型的方法时这在某种程度上是可能的,但感觉不对并且会扰乱请求处理程序的输入。
@app.get("/") -> FooModel:
return FooModel(**{"bar": "baz"}).dict(by_alias=False)
Run Code Online (Sandbox Code Playgroud)
我觉得应该可以在配置类中设置它,但我找不到正确的选项。
我的 FastAPI 调用未以正确的模型格式返回数据Response。它以数据库模型格式返回数据。
我的数据库模型:
class cat(DBConnect.Base):
__tablename__ = 'category'
__table_args__ = {"schema": SCHEMA}
cat_id = Column('cat_id',UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
cat_desc = Column('cat_desc', TEXT, nullable=True)
cat_h__l_name = Column('cat_h_l_name', TEXT, nullable=True)
Run Code Online (Sandbox Code Playgroud)
我的 Pydantic 模型:
class CamelModel(BaseModel):
class config:
alias_generator = to_camel
allow_population_by_field_name = True
class cat(CamelModel):
cat_id =Field(alais='CatID', readonly=True)
cat_description =Field(alias='CatDescription')
cat_h__l_name = Field(alias='CatName')
class config:
orm_mode= True
Run Code Online (Sandbox Code Playgroud)
我的 API 调用:
@router.patch('/cat/{id}/', response_model = 'cat')
def update_cat(response= Response, params: updatecat = Depends(updatecat)):
response_obj = { resonse_code: status.HTTP_200_OK,
response_obj : {}
} …Run Code Online (Sandbox Code Playgroud) 我需要为 Pydantic 对象指定一个 JSON 别名。它根本不起作用。
from pydantic import Field
from pydantic.main import BaseModel
class ComplexObject(BaseModel):
for0: str = Field(None, alias="for")
def create(x: int, y: int):
print("was here")
co = ComplexObject(for0=str(x * y))
return co
co = create(x=1, y=2)
print(co.json(by_alias=True))
Run Code Online (Sandbox Code Playgroud)
这个的输出是{"for" : null而不是{"for" : "2"}
这是真的吗?这样一个简单的用例怎么可能不起作用?