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

DRF测试返回HTTP_201_CREATED但测试数据库未生成模型实例

问题排查结论

核心根因

序列化器ItemCreateSerializer的create方法没有实现数据持久化逻辑:你当前的代码仅实例化了Item模型对象,未调用保存方法将数据写入数据库,因此接口校验全部通过返回201状态码,但数据实际未落地。

错误代码

def create(self, validated_data):
    #Remove price_type value since it is not a field in the model
    #We used to determine th price type on the serializer only
    validated_data.pop('price_type')
    return Item(**validated_data)

修正方案

将create方法调整为以下任意一种写法即可:

def create(self, validated_data):
    validated_data.pop('price_type')
    # 写法1:实例化后手动调用save
    item = Item(**validated_data)
    item.save()
    return item

    # 写法2:直接使用模型管理器的create方法(更简洁)
    # return Item.objects.create(**validated_data)

补充说明

你遇到的返回201但无数据的现象符合DRF的运行逻辑:CreateAPIView只要序列化器校验通过、create方法返回了模型实例,就会判定创建成功并返回201状态码,不会额外校验实例是否已写入数据库。

可选优化

视图ItemCreateAPIView的perform_create方法中调用的check_object_permissions是多余逻辑:创建资源时还未生成实例对象,该方法在这里无实际作用,可以直接删除。


内容的提问来源于stack exchange,提问作者Tony Ayoub

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:30:00