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

Django报错TypeError: 'ModelBase' object is not iterable 求解决

解决TypeError at /check 'ModelBase' object is not iterable错误

错误原因分析

你遇到的错误核心是遍历了模型类本身而非查询集:

  • 在check视图中,你先获取了查询集dishs = dish.objects.all(),但循环时却写了for dishs in dish:,这里的dish是定义的模型类(ModelBase对象),它不可迭代,直接触发报错。
  • 循环变量名和查询集变量名重复(都叫dishs),会覆盖原查询集,后续传给模板的dishs会变成单个模型实例,也会引发后续渲染问题。
  • 额外问题:models.py中dish_id = models.AutoField缺少括号,未完成字段实例化,会导致数据库迁移异常。

修正后的代码

views.py 修正

def check(request):
    dishs = dish.objects.all()
    # 遍历查询集,用独立变量名避免覆盖原查询集
    for dish_item in dishs:
        print(dish_item.dish_name)
    params = {'dish': dishs}
    return render(request, "card/check.html", params)

models.py 修正(dish_id字段)

class dish(models.Model):
    # AutoField需要加括号实例化,指定primary_key=True明确主键作用
    dish_id = models.AutoField(primary_key=True)
    dish_name = models.CharField(max_length=255, blank=True, null=True)
    dish_category = models.CharField(max_length=255, blank=True, null=True)
    dish_size = models.CharField(max_length=7, blank=True, null=True)
    dish_price = models.IntegerField(blank=True, null=True)
    dish_description = models.CharField(max_length=255, blank=True, null=True)
    dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) 
    dish_date = models.DateField()

    def __str__(self):
        return self.dish_name

补充说明

  1. 遍历数据库数据时,必须操作dish.objects.all()返回的查询集(即代码中的dishs),而非模型类dish本身。
  2. 变量命名尽量避免重复,保持语义清晰,比如用dish_item作为循环中的单个菜品实例变量。
  3. Django模型字段必须实例化(加括号),AutoField作为主键使用时,加上primary_key=True是更规范的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:00:59