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

使用pytest测试Django REST API时遇tuple index out of range错误

解决pytest+django_db装饰器导致的'tuple index out of range'错误

先修正测试代码的明显笔误

你测试代码里的Model是未定义的,应该替换成导入的VisualModelTableColumn:

import pytest
from report_tenant.models import VisualModelTableColumn


@pytest.mark.django_db
def test_visual_model_table_column_table():
    col = VisualModelTableColumn.objects.create(key_1=1, key_2=1, key_5=1, key_3=1, key_4=1)
    assert True == True

排查核心错误的可能原因

1. 模型Meta类的ordering配置问题

如果VisualModelTableColumn的Meta类里设置了空元组的ordering,比如:

class Meta:
    ordering = ()

这会触发Django内部处理排序时的索引越界错误,改成合法的字段排序(比如ordering = ('key_1',))或者直接删除ordering配置。

2. 字段choices定义错误

检查模型中是否有字段的choices参数使用了格式不正确的元组,比如空元组、单元素元组,或者每个选项不是(值, 显示文本)的二元组。例如:

# 错误示例
status = models.IntegerField(choices=())
# 正确示例
status = models.IntegerField(choices=((1, '正常'), (2, '禁用')))

3. 模型自定义方法中的元组操作错误

检查VisualModelTableColumn的save()、clean()或其他自定义方法,是否有访问元组索引时越界的代码,比如my_tuple[0]但my_tuple是空的。

4. 版本兼容性问题

确认pytest-django和你的Django版本匹配:

  • Django 4.x 需搭配 pytest-django >= 4.5.0
  • Django 3.x 需搭配 pytest-django >= 3.9.0
    可以通过pip list查看版本,必要时升级:
pip install --upgrade pytest-django

内容的提问来源于stack exchange,提问作者Shakya Peiris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:35:10