0

I don't see any conflicts with the following. What am I doing wrong? I get the following error ImportError: cannot import name 'Business' from 'business.models' I assume maybe I am doing some type of circular loop, but I do not see it.:

#links/models.py
from django.db import models

class LinkType(models.Model):
    link_type = models.CharField(max_length=30)

    def __str__(self):
        return self.link_type

from business.models import Business

class Link(models.Model):
    name = models.CharField(max_length=60)
    business = models.ForeignKey(Business, on_delete=models.CASCADE)
    link_type = models.ForeignKey(LinkType, on_delete=models.CASCADE)

    class Meta:
        unique_together = ['business', 'link_type']

    def __str__(self):
        return self.name

#business/models.py
from django.db import models
from links.models import LinkType

class Business(models.Model):
    name = models.CharField(max_length=255)
    main_link_type = models.ForeignKey(LinkType, on_delete=models.CASCADE) 

    def __str__(self):
        return self.name
Padoga
  • 495
  • 3
  • 18

2 Answers2

3

Yes, there is a circular import. In the business model, you are importing the links model and in the links model you are importing the business model.

Here are links to similar questions which might help:

ImportError: Cannot import name X

Django cannot import name x

twothreezarsix
  • 375
  • 3
  • 13
2

Django related field accepts the to parameter as string too. The value should be in app_name.ModelName format.

class Link(models.Model):
    business = models.ForeignKey('business.Business', on_delete=models.CASCADE)
   # rest of your code

# business/models.py

class Business(models.Model):
    main_link_type = models.ForeignKey('links.LinkType', on_delete=models.CASCADE)
   # rest of your code
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Can you add to your answer what imports I need to make. For example above the `Link` model do I need to do `from business.models import Business`? – Padoga Jul 21 '20 at 08:13
  • 2
    Remove both the imports in the Business and LinkType models. Then update the above two lines. Removing just one import might also work. Maybe check that too. – twothreezarsix Jul 21 '20 at 08:24
  • 1
    In my answer the `to` is string and it doesn't involve or rely on any kind imports. @Padoga . Also, follow `twothreezarsix`'s comment. – JPG Jul 21 '20 at 08:28