Django迁移异常:注册Recipes模型遇'type'不可迭代错误求助
Django模型注册报错:TypeError: 'type' object is not iterable
问题根源
你的Recipes模型类没有继承Django核心的models.Model,导致它只是一个普通Python类,而非Django认可的模型类。当admin.site.register()尝试处理这个普通类时,内部逻辑会把它当成可迭代对象去遍历,从而抛出'type' object is not iterable错误。
解决方法
修改models.py,让Recipes类继承models.Model即可——这是所有Django模型的必备要求。
修正后的代码示例
models.py
from django.db import models # Create your models here. class Recipes(models.Model): title = models.TextField() ingredients = models.TextField() directions = models.TextField() rating = models.IntegerField()
admin.py(无需修改,保持原代码即可)
from django.contrib import admin # Register your models here. from .models import Recipes admin.site.register(Recipes)
验证步骤
- 保存修改后的代码
- 运行数据库迁移命令:
python manage.py makemigrations python manage.py migrate
- 重新启动Django服务,访问后台即可看到
Recipes模型已正常注册。
内容的提问来源于stack exchange,提问作者yourmaster12321-at-hyphens
相关产品推荐
相关产品推荐

