我正在尝试使用 tortoise orm 更新数据库中的记录。我的代码如下:
async def update(
self,
id: Any,
obj_in: UpdateSchemaType
) -> ModelType:
db_obj: ModelType = await self.model.filter(id = id).first()
data_update = jsonable_encoder(obj_in, exclude_unset=True)
db_obj_update = await db_obj.update_from_dict(data_update)
return db_obj_update
UpdateSchemaType 是一个 pydantic 模型,ModelType 是一个乌龟模型。
我正在使用路径操作并放入fastapi:
@users_router.put(
'/{user_id}',
name = "Update user"
)
async def update_user(user_id: int, user_update: schemas.UserUpdate):
'Update user'
return await crud.user.update(user_id, user_update)
当我运行我的 api 时,我没有收到任何错误,但注册表没有更新!我做错了什么?或者我应该如何做才能使其有用且高效?
来自
update_from_dict
方法的文档:
这将忽略任何额外的字段,并且不会用它们更新模型, 但会在错误类型或更新多实例关系时引发错误。
所以你需要在
await object.save()
之后制作update_from_dict
。
task = await Task.create(
name="First task",
description="First task description",)
for i in range(0, 5):
await Task.create(name="s", description="s"+str(i))
task = await Task.get(id=1)
print(task.description)
# Output: First task description
task.description = "new description"
await task.save()
# Close 'await' call in brackets for get object, not Queryset type
print((await Task.get(id=1)).description)
# Output: new description