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

Django数据库填充调用API时出现TypeError: string indices must be integers如何解决

报错原因

你触发这个错误的核心原因是遍历逻辑和接口返回结构不匹配:

  • get_nrel() 函数返回的是完整的JSON字典对象,直接用 for i in get_nrel() 遍历字典时,循环变量i拿到的是字典的顶层键名(字符串类型,比如"inputs"、"outputs"这类字符串),你尝试用字符串i取下标['utility_name']自然会触发string indices must be integers报错。
  • 你需要的所有字段都存在返回JSON的outputs节点下,不需要循环遍历,直接取对应节点的值即可。

额外待修正的小问题

你请求头里的Content-Type写法错误,把冒号写成了等号,虽然本次报错不是这个原因,但也需要修正避免后续接口请求异常。

修正后的代码

import requests
from django.core.management.base import BaseCommand
from nrel_app.models import Nrel


def get_nrel():
    url = 'https://developer.nrel.gov/api/utility_rates/v3.json?api_key=DEMO_KEY&lat=35.45&lon=-82.98'
    # 修正请求头写法
    r = requests.get(url, headers={'Content-Type': 'application/json'})
    res = r.json()
    # 直接返回你需要的outputs节点
    return res.get('outputs', {})

def seed_nrel():
    # 不需要循环,直接取返回的outputs数据
    data = get_nrel()
    # 加个判空避免接口返回异常时报错
    if not data:
        print("未获取到有效数据")
        return
    nrel_obj = Nrel(
        utility_name = data['utility_name'],
        company_id = data['company_id'],
        utility_info = data['utility_info'], # 注意:如果你的Nrel模型中utility_info字段不是JSONField,需要先转成字符串格式再存储
        residential = data['residential'],
        commercial = data['commercial'],
        industrial = data['industrial'],
    )
    nrel_obj.save()

class Command(BaseCommand):
    def handle(self, *args, **options):
        seed_nrel()
        print("Completed.")

补充说明

如果你的Nrel模型中utility_info字段定义的是字符串类型,需要把utility_info = data['utility_info']改成utility_info = str(data['utility_info'])或者按你需要的格式做序列化后再存储。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:15:03