Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to avoid circular imports

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
like image 931
mfalcon Avatar asked Jun 08 '11 20:06

mfalcon


People also ask

How do I fix the circular import error in python?

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.

Why are circular imports bad?

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.

How do I get rid of cyclic dependency in python?

The easiest way to fix this is to move the path import to the end of the node module. Save this answer.


1 Answers

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.

like image 107
Cat Plus Plus Avatar answered Oct 14 '22 20:10

Cat Plus Plus