Django访问/index时报'ModelBase'对象不可迭代TypeError错误如何解决
故障原因分析
- 核心错误:你在POST分支里直接遍历
staff模型类本身,Django的ORM模型类是ModelBase类型的对象,本身不可迭代,必须调用staff.objects.all()获取可迭代的查询集才能遍历 - 次要错误1:视图代码里误用了Django模板语法
{{staffs.id}},{{}}是模板渲染专用语法,不能直接写在Python视图文件里,字符串拼接直接使用Python原生语法即可 - 次要错误2:变量命名存在歧义,循环变量名和模型类、后续查询集变量名重复,容易引发后续逻辑混乱
修正后的视图代码
import datetime from .models import staff, attendance, amount # 确保你已经正确导入对应模型 from django.shortcuts import render def index(request): if request.method == "POST" : # 先获取所有员工的查询集再遍历 for staff_obj in staff.objects.all() : # 改用Python原生字符串拼接,同时将int类型的id转为字符串 stf_if = 'staff_id' + str(staff_obj.id) staff_id = request.POST[stf_if] at_if = 'attendance' + str(staff_obj.id) attendances = request.POST[at_if] date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staffs = staff.objects.all() attendances = attendance.objects.all() amounts = amount.objects.all() count_id = staff.objects.latest('id') date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'amount': amounts, 'count_id': count_id, 'date': date})
补充注意事项
- 建议模型类命名遵循Python大驼峰命名规范,比如
Staff、Attendance,和实例变量做明确区分,减少命名混淆 - 可以用
request.POST.get(参数名)替代直接取request.POST[参数名],避免提交的参数不存在时抛出异常
内容的提问来源于stack exchange,提问作者Path Parakh
相关产品推荐
相关产品推荐

