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

Pytest传递字典列表至POST请求时失败的问题排查

解决批量创建测试用例的AttributeError问题

问题根源

测试用例发送POST请求时,直接把列表传给了data参数。DRF的APIClient.post()方法默认将data参数当作表单数据处理,会尝试调用字典的items()方法解析,而列表没有这个属性,因此触发报错。

修正方法

把批量数据通过json参数传入,而非data参数:

错误示例(引发报错)

def test_batch_create_manufacturers(client):
    payload = [{"name": "厂商1"}, {"name": "厂商2"}]
    response = client.post("/api/manufacturers/", payload, format="json")

正确示例

def test_batch_create_manufacturers(client):
    payload = [{"name": "厂商1"}, {"name": "厂商2"}]
    response = client.post("/api/manufacturers/", json=payload)

如果使用的是DRF 3.10以下的旧版本,可以手动将列表序列化为JSON字符串并指定content_type:

import json

def test_batch_create_manufacturers(client):
    payload = [{"name": "厂商1"}, {"name": "厂商2"}]
    response = client.post(
        "/api/manufacturers/",
        data=json.dumps(payload),
        content_type="application/json"
    )

额外验证点

  1. 确保视图/序列化器确实支持接收列表格式请求体:

    • 自定义CreateModelMixin中需处理isinstance(serializer.validated_data, list)的场景
    • 在视图的get_serializer方法中,根据请求体是否为列表,传递many=True参数给序列化器
  2. 测试前清空数据库避免重复数据干扰:

from django.test import TestCase
from myapp.models import Manufacturer

class ManufacturerTests(TestCase):
    def setUp(self):
        Manufacturer.objects.all().delete()
    
    def test_batch_create(self):
        # 测试代码逻辑
        pass

内容的提问来源于stack exchange,提问作者alucor-it

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:45:56