Trying to Avoid Circular Import

I recently split the app into two separate ones because I had 15 models. I had a "circular import error." To solve this problem, I tried to write this:

from django.db import models

class App1Model(models.Model):
    app2model = models.ForeignKey(app2.App2Model)

The error I get is: "NameError: name" app2 "not defined." But application 2 is correctly added to installed applications and to the path.

project
    -app1
        --models.py
    -app2
        --models-py
+5
source share
3 answers

ForeignKeycan take a string as an argument, i.e. models.ForeignKey('app2.App2Model'). Of course, you should try to develop your code to avoid any circular dependencies in the first place.

+13
source

Cat Plus Plus , , :

try:
    import app.model
except ImportError:
    pass
+2

You still need the import statement

import app2.App2Model

But if app2 imports application 1, you will get an error, as you mentioned.

+1
source

All Articles