Django序列化器添加字典报错:list indices must be integers or slices
问题原因与解决方案
为什么会报错?
你遇到的list indices must be integers or slices, not str错误,根源很直观:ListAPIView的list方法返回的response.data是一个列表(数组)(对应你给出的序列化器输出是[ {...}, {...} ]这种格式),而你试图用字符串'schedule'作为索引给列表赋值——列表只能用整数索引(比如response.data[0])或者切片(比如response.data[:2])访问元素,完全不支持用字符串当键,所以直接触发了报错。
另外提一句:你写的期望输出格式其实不符合JSON规范(列表里不能直接放"schedule": {}这种键值对),我猜你真正想要的是返回一个包含原函数列表和schedule信息的结构化对象。
解决方案
根据你的实际需求,有两种可行的处理方式:
方案1:包装成字典返回(推荐,结构更清晰)
把原来的函数列表和schedule数据一起放到一个新字典里,替换掉原有的response.data,这样返回的JSON结构更合理,前端也更容易解析:
def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) user = self.request.user cluster = Cluster.objects.filter(user_id=user.id, id=self.kwargs["cluster_id"]).first() schedule = Schedule.objects.filter(clusters__in=[cluster]).values().first() # 用字典包装原数据和schedule response.data = { "functions": response.data, # 原函数列表 "schedule": schedule # 新增的schedule信息 } return response
返回的JSON格式会是:
{ "functions": [ // 原有序列化器内容 ], "schedule": { "id": 7, "user_id": 3, // ... schedule其他字段 } }
方案2:将schedule追加到列表末尾(不推荐,结构混乱)
如果你确实需要让schedule出现在列表里(比如作为最后一个元素),可以直接把它追加到列表末尾,但这种方式返回的列表会混合两种不同类型的业务数据,后续维护和前端解析都会有麻烦:
def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) user = self.request.user cluster = Cluster.objects.filter(user_id=user.id, id=self.kwargs["cluster_id"]).first() schedule = Schedule.objects.filter(clusters__in=[cluster]).values().first() # 把schedule追加到原列表末尾 response.data.append(schedule) return response
返回的JSON格式是:
[ { // 原函数对象 }, { "id": 7, "user_id": 3, // ... schedule字段 } ]
内容的提问来源于stack exchange,提问作者Derrick Omanwa
相关产品推荐
相关产品推荐

