如何使用 tortoise orm 更新记录?

问题描述 投票:0回答:2

我正在尝试使用 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 时,我没有收到任何错误,但注册表没有更新!我做错了什么?或者我应该如何做才能使其有用且高效?

python database fastapi pydantic tortoise-orm
2个回答
3
投票

来自

update_from_dict
方法的文档:

这将忽略任何额外的字段,并且不会用它们更新模型, 但会在错误类型或更新多实例关系时引发错误。

所以你需要在

await object.save()
之后制作
update_from_dict


0
投票
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

https://habr.com/ru/articles/829222/

© www.soinside.com 2019 - 2024. All rights reserved.