You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI搭配Tortoise ORM创建购物车报AttributeError错误如何解决?

问题原因

这个AttributeError: 'int' object has no attribute '_saved_in_db'错误触发的核心是Tortoise ORM的外键字段传值规则不符合要求:

你在调用Cart.create()方法时,直接给user、product这两个外键字段传入了int类型的ID值,但Tortoise ORM的ForeignKeyField默认预期接收的是关联模型的已保存实例,它会默认校验实例的_saved_in_db属性判断实例是否合法,int类型自然没有这个属性,因此触发报错。

解决方案

有两种可行的修复方式,推荐使用第一种,性能更高:

方案1:外键字段直接传ID时添加_id后缀

Tortoise ORM支持直接给外键传ID值,只需要在外键字段的名称后追加_id后缀即可,无需额外查询关联表数据。
修改路由层的Cart.create调用参数即可:

@router.post('/create', status_code=status.HTTP_201_CREATED)
async def create_cart(
    cart: CartCreate, 
    user: User = Depends(get_current_user)
) -> CartSchema:
    cart_obj = await Cart.create(
        # 外键传ID时加_id后缀
        user_id=user.id,
        product_id=cart.product_id,
        quantity=cart.quantity
    )
    return CartSchema.from_orm(cart_obj)

方案2:传入关联模型的实例对象

如果需要先校验关联数据是否存在,可以先查询出对应的实例再传入create方法:

from fastapi import HTTPException

@router.post('/create', status_code=status.HTTP_201_CREATED)
async def create_cart(
    cart: CartCreate, 
    user: User = Depends(get_current_user)
) -> CartSchema:
    # 校验商品是否存在
    product = await Product.get_or_none(id=cart.product_id)
    if not product:
        raise HTTPException(status_code=404, detail="商品不存在")
    cart_obj = await Cart.create(
        user=user,
        product=product,
        quantity=cart.quantity
    )
    return CartSchema.from_orm(cart_obj)
验证修复效果

修改完成后重新发起添加购物车的请求,即可正常创建购物车记录,不会再触发该属性错误。


内容的提问来源于stack exchange,提问作者Shayan-9248

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:24:03