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

Django创建Product报错:无法将字符串分配给Category外键字段

问题解决:Cannot assign "'Sample Category'": "Product.category" must be a "Category" instance

问题原因

Product模型的category字段是外键,关联到Category模型,创建Product时必须传入Category实例或对应类别的主键ID,你当前传入的字符串"Sample Category"不符合外键字段的要求。

解决方案

方法1:使用已存在的Category实例

先通过名称查询获取对应的Category实例,再传入Product创建方法:

@api_view(['POST'])
def createProduct(request):
    user = request.user
    
    # 查询或自动创建指定名称的Category(避免类别不存在的异常)
    category, created = Category.objects.get_or_create(name="Sample Category")
    
    product = Product.objects.create(
        user=user,
        name_geo="Sample Name",
        category=category,  # 传入Category实例
        price=0,
        brand='Sample Brand',
        countInStock=0,
    )

    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)
  • get_or_create会先查找名称为"Sample Category"的类别,存在则返回实例;不存在则自动创建新类别并返回实例。
  • 若确定类别一定存在,也可使用Category.objects.get(name="Sample Category"),但需注意捕获DoesNotExist异常。

方法2:传入Category的主键ID

若已知目标Category的主键ID(比如从前端接收),可直接传入ID值:

@api_view(['POST'])
def createProduct(request):
    user = request.user
    category_id = 1  # 假设对应"Sample Category"的主键是1
    
    product = Product.objects.create(
        user=user,
        name_geo="Sample Name",
        category_id=category_id,  # 直接传入主键ID
        price=0,
        brand='Sample Brand',
        countInStock=0,
    )

    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)

额外注意:修正模型默认值问题

你的Product模型中category字段设置了default=0,但Category的主键是自增AutoField,默认值0大概率不存在对应类别,易引发后续异常。建议修改为:

# 允许category为空(根据业务需求调整)
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)

# 或提前创建默认类别,将default设为该类别的主键ID
# 比如先在数据库添加"默认类别",主键为1,再设置:
# category = models.ForeignKey(Category, default=1, on_delete=models.CASCADE)

内容的提问来源于stack exchange,提问作者temo pkhakadze

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:55:13