0

The title for this question may be confussing.I don't know what title should be given to this problem.

I have two models files ==> models.py in app a and models.py in app b models.py has class A in app a models.py has class B in app b

Both classes extend django.db.models.Model i.e. these classes are making database tables

I want to import class A from models.py from app a which imports class B from models.py in app b.

I want to say that both classes are using each other.

if I code like this: models.py in app a==>

from b.models import B

models.py in app b ==>

from a.models import A

then I am getting import error that B is not defined.

how can I import both classes in both files?

ferrangb
  • 2,012
  • 2
  • 20
  • 34

2 Answers2

6

You can create foreign key to model without importing it. Instead of model class pass a string with app name and model name. See the docs for ForeignKey:

class B(models.Model):

    a = models.ForeignKey('a.A')

If you want to access such model somewhere in the code then import it inside a function:

class B(models.Model):

    def some_method(self):
        from a.models import A
        ...
catavaran
  • 44,703
  • 8
  • 98
  • 85
0

This is a circular dependency question rather. You an check Circular dependency in Python answer.

In short, you should either try to change your class organization to prevent this or you can use imports within functions to avoid import errors.

Community
  • 1
  • 1
Benjamin Cbr
  • 536
  • 4
  • 13