You need to enable JavaScript to run this app. 开发API时出现'ModelBase' object is not iterable错误,附代码求解决
优惠活动
大模型
产品
解决方案
定价
更多

开发API时出现'ModelBase' object is not iterable错误,附代码求解决

解决'ModelBase' object is not iterable 错误

错误根源在views.py的序列化步骤:你传入了Watchlist模型类本身,而不是查询得到的可迭代数据集movies。模型类属于ModelBase类型,本身不可迭代,因此触发报错。

修正后的views.py代码:

@api_view(['GET'])
def home(request):
    if request.method == 'GET':
        movies = Watchlist.objects.all()
        serializer = WatchlistSerializer(movies, many=True)  # 将Watchlist替换为movies
        return Response(serializer.data)

说明:Watchlist.objects.all()返回的是可迭代的QuerySet对象,满足序列化器对数据源的要求;而直接传入Watchlist是模型类,并非可迭代的数据集,这就是报错的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:50:13