KeykoYume
KeykoYume

Reputation: 2645

How to solve circular imports

I have 2 models ai_output which defines AIOutput and manual_overwrite with ManualOverwrite which are both importing each other and so I get the following error:

from main.models.manual_overwrite import ManualOverwrite

ImportError: cannot import name ManualOverwrite

The only solution I could find through the django docs was solving it by removing the import of a class in one of the files, and replacing it with a string containing the name of the class

and so this:

aioutput = models.ForeignKey(AIOutput, null=True, blank=True)

became this:

aioutput = models.ForeignKey('ai_output.AIOutput', null=True, blank=True)

But now I get that:

main.ManualOverwrite.aioutput: (fields.E300) Field defines a relation with model 'ai_output.AIOutput', which is either not installed, or is abstract.

Any idea how to solve the issue with circular imports? Any tip would be greatly appreciated!

Upvotes: 1

Views: 117

Answers (1)

hspandher
hspandher

Reputation: 16733

Most likely, you forgot to add app containing AIOutput model to INSTALLED_APPS. If that is not the case, moving another app above this one in INSTALLED_APPS should solve the problem. On a side note, circular imports often occur when two related things are part of different apps and is probably a sign that the design might be improved such that related components stay in the same app. With that said, it is not always the case.

Upvotes: 2

Related Questions