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

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. 验证修复结果

  1. 关闭当前运行的Python Shell
  2. 重新启动Shell:
    python manage.py shell
    
  3. 尝试导入模型:
    from inventory.models import Ingredient
    

此时应能成功导入,不再触发ImportError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:10:19