【问题标题】:cannot import name in django rest framework无法在 django rest 框架中导入名称
【发布时间】:2020-10-13 22:55:50
【问题描述】:

应用结构

areas models.py

from django.db import models
from products.models import ProductModel

class ProductionLine(models.Model):
    name = models.CharField(max_length = 50, unique=True)

产品模型.py

from django.db import models
from areas.models import ProductionLine

class ProductModel(models.Model):
    name= models.CharField(max_length = 255, unique=True)
    productionLine = models.ForeignKey(ProductionLine,on_delete=models.CASCADE)


我正在尝试导入 ProductionLine,但是当我导入 ProductionLine 时出现错误:

  • 文件“/app/areas/models.py”,第 2 行,在 *
  • 从 products.models 导入 ProductModel*
  • ImportError: 无法导入名称“ProductModel”*

当我在 products.models 中删除 ProductionLine 的导入时,一切正常。我不明白

【问题讨论】:

标签: django django-models django-rest-framework


【解决方案1】:

这里你在 products models.py 中导入ProductionLine 并在area.py 中导入ProductModel,这会导致circular dependency,在这种情况下,你可以使用模型字符串来代替:

from django.db import models
# comment this line
# from areas.models import ProductionLine

class ProductModel(models.Model):
    name= models.CharField(max_length = 255, unique=True)
    productionLine = models.ForeignKey('areas.ProductionLine',on_delete=models.CASCADE)

【讨论】:

    【解决方案2】:

    Django - Circular model import issue 可能重复

    在 ProductModel 中,对于生产线,执行以下操作:

    productionLine = models.ForeignKey('areas.ProductionLine', on_delete=models.CASCADE)
    

    同时确保您在 INSTALLED_APPS 下的 settings.py 中列出了这两个应用

    【讨论】:

      【解决方案3】:

      我猜你没有将你的应用程序插入到你的installed_appssettings.py

      settings.py

      INSTALLED_APPS = [
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.messages',
          'django.contrib.staticfiles',
      
          # Custom Apps
          'products',
          'areas',
      ]
      
      Your import statements look just fine.
      

      【讨论】:

        猜你喜欢
        • 2015-10-08
        • 1970-01-01
        • 2011-07-11
        • 2015-03-01
        • 2011-12-27
        • 2018-05-29
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多