In Django, why i cannot import a model in an python file created by me in inside the same app?

Question:

I created in Django, in my app an python file for forms and I want to import a model from .models (from the same app).
The problem is when I import the model, it returned an error.

The model is(models.py):

class Article(models.Model):
    title = models.CharField(max_length=100)
    location=models.CharField(max_length=120,null=True,blank=True)
    category=models.CharField(max_length=100,null=True,blank=False)
    slug=models.SlugField(null=True, blank=True, unique=True)
    boddy=models.TextField()
    timestamp = datetime.now()
    update = models.TimeField(auto_now=True)

The problem is in util.py (the python file that i created) :

from .models import Article

The error is:

ImportError: cannot import name ‘Article’ from partially initialized module ‘hello.models’ (most likely due to a circular import) (D:PythonDjangoProjectsmyprojecthellomodels.py)

The python files are in the same app

Asked By: Andrei Tudor

||

Answers:

It seems you’re trying to do what is called a ‘Circular Import’; you can’t do that.

Your App is separated in modules and packages. (.py files and folders with a __init__.py file inside), and when you import a module into another module, python will run that entire module and set it into memory.

If in models.py you run

from ./.. import utils

… and in utils.py

from .models import Article

You will end up importing a module into another then into another recursively, resulting in a Memory Overflow.

To prevent that from happening, Django comes with a few checks that prevent that circular import.

A good way to prevent that is to separate your classes into smaller modules, so you only import that module.
On the other hand, if you’re to refer to Foreign Keys, you can use Django built-in Lazy Reference by using '<app_name>.<ClassName>' under quotes.

By doing so, you don’t have to import the module, hence, there’s no risk of circular import.

Answered By: Gabriel Santos