Recently I splitted an app into two separate ones because I had 15+ models in it. I had got the "circular import error". To solve this I tried writing this:
from django.db import models
class App1Model(models.Model):
app2model = models.ForeignKey(app2.App2Model)
The error I'm getting is: "NameError: name 'app2' is not defined". But app2 is correctly added into installed apps and into the path.
project
-app1
--models.py
-app2
--models-py
If the error occurs due to a circular dependency, it can be resolved by moving the imported classes to a third file and importing them from this file. If the error occurs due to a misspelled name, the name of the class in the Python file should be verified and corrected.
Circular dependencies can cause quite a few problems in your code. For example, it may generate tight coupling between modules, and as a consequence, reduced code reusability. This fact also makes the code more difficult to maintain in the long run.
The easiest way to fix this is to move the path import to the end of the node module. Save this answer.
ForeignKey
can take a string as an argument, i.e. models.ForeignKey('app2.App2Model')
. Of course, you should try to design your code to avoid any circular dependencies in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With