You need to enable JavaScript to run this app. Django单元测试传递嵌套字典参数时view接收数据异常问题
优惠活动
大模型
产品
解决方案
定价
更多

Django单元测试传递嵌套字典参数时view接收数据异常问题

问题根因

HTTP表单默认格式(application/x-www-form-urlencoded)本身不支持嵌套字典结构,Django对该格式的参数解析会自动将嵌套字典打平,才会出现你看到的参数值被包裹为数组、filter_options仅保留内层键的异常情况。

解决方法

方法1:使用DRF自带测试类(推荐)

你代码中添加的format='json'参数仅在使用DRF提供的APITestCase测试类时生效,它会自动将传入的字典序列化为JSON格式发送,后端会对应解析为正确的嵌套结构。
修改测试文件代码即可:

# 导入DRF测试基类
from rest_framework.test import APITestCase

# 测试类继承APITestCase而非Django原生TestCase
class YourTestClass(APITestCase):
    def test_search_with_full_name(self):
        data = {'class_id': '1', 'filter_options': {'full_name': 'user 1'}}
        response = self.client.post('/api/students', data, format='json')
        self.assertEqual(response.status_code, 200)

方法2:Django原生Client手动序列化JSON

如果要使用Django原生测试Client,可以手动将数据序列化为JSON字符串后发送,同时指定请求内容类型:

import json
from django.test import TestCase

class YourTestClass(TestCase):
    def test_search_with_full_name(self):
        data = {'class_id': '1', 'filter_options': {'full_name': 'user 1'}}
        response = self.client.post(
            '/api/students',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)

可选检查项

如果你手动修改过DRF的全局配置,需要确认DEFAULT_PARSER_CLASSES中包含rest_framework.parsers.JSONParser,默认配置默认已开启该解析器无需额外调整。

修改完成后request.data就会返回正常的嵌套字典结构,filter_options['full_name']可以正常取值。

内容的提问来源于stack exchange,提问作者Lewis Tran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 11:45:07