alpha
alpha

Reputation: 594

cannot import name in django rest framework

Structure of app

enter image description here

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)

products models.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)


I'm trying to import ProductionLine, but when i import ProductionLine i have an error :

And when i delete the import of ProductionLine in products.models, everything works. I don't understand

Upvotes: 0

Views: 2696

Answers (4)

Razz
Razz

Reputation: 1

Make sure you impoirt APIView from views module in rest_framework:

from rest_framework.views import APIView

Upvotes: 0

Sukanya Pai
Sukanya Pai

Reputation: 824

Possible duplicate of Django - Circular model import issue

In ProductModel, for productionLine, do this:

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

Also ensure that you have both the apps listed in settings.py under INSTALLED_APPS

Upvotes: 1

minglyu
minglyu

Reputation: 3327

here you import ProductionLine in products models.py and also import ProductModel in areas.py, which causes circular dependency, in this case, you can use model string instead:

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)

Upvotes: 1

JSRB
JSRB

Reputation: 2613

I guess you didn't insert your apps into installed_apps in your settings.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.

Upvotes: -1

Related Questions