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

Django loaddata导入JSON遇DeserializationError:字符串索引需为整数

Django loaddata 导入JSON数据时出现 TypeError: string indices must be integers, not 'str' 错误解决

问题场景

执行python manage.py loaddata app/fixtures/data.json导入JSON数据到SQLite时,触发TypeError: string indices must be integers, not 'str'错误,进而引发django.core.serializers.base.DeserializationError。

涉及的models.py代码

from django.db import models

# Create your models here.
class Game(models.Model):
    team=models.CharField(max_length=50)
    team1=models.CharField(max_length=50)
    team_score=models.IntegerField()
    team1_score=models.IntegerField()
    box=models.URLField()
    box1=models.URLField()

class Team(models.Model):
    game_set=models.ForeignKey(Game,on_delete=models.CASCADE,related_name='team_set')
    points=models.IntegerField()
    field_goals=models.IntegerField()
    field_goals_attempts=models.IntegerField()
    field_goals_percentage=models.FloatField()
    three_pointers_made=models.IntegerField()
    three_point_attempts= models.IntegerField()
    three_point_percentage=models.FloatField()
    free_throws_made= models.IntegerField()
    free_throw_attempts= models.IntegerField()
    free_throw_percentage=models.FloatField()
    offensive_rebounds= models.IntegerField()
    total_rebounds= models.IntegerField()
    assists= models.IntegerField()
    personal_fouls= models.IntegerField()
    steals= models.IntegerField()
    turnovers= models.IntegerField()
    blocks= models.IntegerField()

class Field(models.Model):
    game_set = models.ForeignKey(Game, on_delete=models.CASCADE)
    author= models.CharField(max_length=100)
    body=models.TextField(max_length=100)
    created_at= models.DateTimeField(auto_now_add=True)

完整报错信息

python manage.py loaddata app/fixtures
CommandError: No fixture named 'fixtures' found.
(.venv) PS C:\Users\ambai\PycharmProjects\Task1> python manage.py loaddata app/fixtures/data.json
Traceback (most recent call last):
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer
    yield from PythonDeserializer(objects, **options)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\python.py", line 114, in Deserializer
    Model = _get_model(d["model"])
                       ~^^^^^^^^^
TypeError: string indices must be integers, not 'str'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ambai\PycharmProjects\Task1\manage.py", line 22, in <module>
    main()
  File "C:\Users\ambai\PycharmProjects\Task1\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\base.py", line 459, in execute
    output = self.handle(*args, **options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle
    self.loaddata(fixture_labels)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata
    self.load_label(fixture_label)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 251, in load_label
    for obj in objects:
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer
    raise DeserializationError() from exc
django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Users\ambai\PycharmProjects\Task1\app/fixtures\data.json':
(.venv) PS C:\Users\ambai\PycharmProjects\Task1> python manage.py makemigrations                 
django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Users\ambai\PycharmProjects\Task1\app/fixtures\data.json':
(.venv) PS C:\Users\ambai\PycharmProjects\Task1> python manage.py makemigrations
No changes detected
(.venv) PS C:\Users\ambai\PycharmProjects\Task1> python manage.py loaddata app/fixtures/data.json
Traceback (most recent call last):
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer
    yield from PythonDeserializer(objects, **options)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\python.py", line 114, in Deserializer
    Model = _get_model(d["model"])
                       ~^^^^^^^^^
TypeError: string indices must be integers, not 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\ambai\PycharmProjects\Task1\manage.py", line 22, in <module>
    main()
  File "C:\Users\ambai\PycharmProjects\Task1\manage.py", line 18, in main    
    execute_from_command_line(sys.argv)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\base.py", line 459, in execute
    output = self.handle(*args, **options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle
    self.loaddata(fixture_labels)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata
    self.load_label(fixture_label)
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\management\commands\loaddata.py", line 251, in load_label
    for obj in objects:
  File "C:\Users\ambai\PycharmProjects\Task1\.venv\Lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer
    raise DeserializationError() from exc

错误原因

该错误核心是JSON fixture结构不符合Django要求。Django序列化器期望接收一个包含特定格式字典的数组:每个字典必须包含model(指定模型路径)、pk(主键值)和fields(模型字段键值对)。当前JSON数据中,序列化器尝试访问字符串的"model"索引,说明数据不是预期的字典结构,可能是顶级为字符串、单个对象,或元素格式不匹配。

解决方案

1. 修正JSON fixture格式

Django要求的标准JSON fixture格式如下:

[
  {
    "model": "app.game",
    "pk": 1,
    "fields": {
      "team": "湖人",
      "team1": "凯尔特人",
      "team_score": 120,
      "team1_score": 115,
      "box": "https://example.com/box1",
      "box1": "https://example.com/box2"
    }
  },
  {
    "model": "app.team",
    "pk": 1,
    "fields": {
      "game_set": 1,
      "points": 120,
      "field_goals": 45,
      "field_goals_attempts": 80,
      "field_goals_percentage": 0.5625,
      "three_pointers_made": 15,
      "three_point_attempts": 30,
      "three_point_percentage": 0.5,
      "free_throws_made": 15,
      "free_throw_attempts": 20,
      "free_throw_percentage": 0.75,
      "offensive_rebounds": 10,
      "total_rebounds": 40,
      "assists": 25,
      "personal_fouls": 12,
      "steals": 8,
      "turnovers": 5,
      "blocks": 3
    }
  },
  {
    "model": "app.field",
    "pk": 1,
    "fields": {
      "game_set": 1,
      "author": "评论员A",
      "body": "这场比赛双方对抗激烈"
    }
  }
]
  • model格式为app_name.ModelName(此处app名称为app,需匹配项目结构)
  • pk为模型主键值,需保证唯一性
  • fields内键名要与models.py定义的字段完全一致,外键字段填写关联对象的pk值

2. 校验JSON语法

使用JSON校验工具检查数据是否存在语法错误(如遗漏逗号、引号不匹配等),避免因格式问题导致解析失败。

3. 分步测试导入

若为大型JSON文件,建议先提取少量数据制作test_data.json,调整格式后执行python manage.py loaddata app/fixtures/test_data.json测试导入,确认无误后再导入完整数据。

4. 检查Django配置

确保app已添加到项目settings.py的INSTALLED_APPS中,避免模型无法被识别。

内容的提问来源于stack exchange,提问作者Ambaig Baig

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 00:29:51