Django导入Ingredient模型报错:无法从inventory.models导入该类
解决Django模型导入错误:ImportError: cannot import name 'Ingredient'
你的问题根源在于models.py中存在字段参数拼写错误,导致Django无法正确解析模型类,进而引发导入失败。以下是具体修复步骤:
1. 修正字段参数拼写错误
代码中有两处DecimalField的参数写错了:
Ingredient类的price_per_unit字段:decimal_place=2→ 应为decimal_places=2(遗漏末尾的s)Purchase类的total_cost字段:decimal_place=2→ 应为decimal_places=2
2. 修复后的完整models.py代码
from django.db import models import datetime class Ingredient(models.Model): name = models.CharField(max_length=100) available_quantity = models.DecimalField(max_digits=10, decimal_places=2) price_per_unit = models.DecimalField(max_digits=10, decimal_places=2) class MenuItem(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) class RecipeRequirement(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity_required = models.DecimalField(max_digits=10, decimal_places=2) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) quantity_purchased = models.DecimalField(max_digits=10, decimal_places=2) total_cost = models.DecimalField(max_digits=10, decimal_places=2)
3. 验证修复结果
- 关闭当前运行的Python Shell
- 重新启动Shell:
python manage.py shell - 尝试导入模型:
from inventory.models import Ingredient
此时应能成功导入,不再触发ImportError。
内容的提问来源于stack exchange,提问作者Michael Carlucci
相关产品推荐
相关产品推荐

