A
A
Artyom Innokentiev2015-10-25 20:16:42
Django
Artyom Innokentiev, 2015-10-25 20:16:42

What is the correct logic for importing modules in such a case?

There are such models:
app1/models.py:

from django.db import models
from app2.models import B
from app3.models import C

class A(models.Model):
      pass

app2/models.py:
from django.db import models
from app1.models import A

class B(models.Model):
    data = models.ForeignKey(A)

app3/models.py:
from django.db import models

class C(models.Model):
    pass

app4/models.py:
from django.db import models
from app1.models import A

class D(models.Model):
    data = models.ForeignKey(models.Model)

There is a cyclic import of modules - as a result, an error during migration.
What should be the correct logic for importing these modules? It's not easy to import like that, arguing that it doesn't work that way. There must be a certain import logic that can be traced in every application.
PS At the same time, all applications contain only those models that relate to them. The base is normalized - there are no repeating fields.
PPS
1) Transferring class A to a separate file is not an option - because a separate file appears, all models must be stored in one place.
2) Moving the import statements after the class declaration in app1 is also not an option - wrong and ugly.
3) I don't want to take out the import statement in the function - it's ugly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lebedev, 2015-10-25
@zymanch

ran into this problem not too long ago. Now my model files look like this:
app2/models.py :

from django.db import models

class B(models.Model):
    data = models.ForeignKey('app1.A')

eliminates unnecessary imports and, IMHO, makes the model code more readable - you can always see which application the model belongs to.
If you need to use class A in the same file, for example, in a method of the same class, then I do this:
from django.db import models
from django.apps import apps

class B(models.Model):
    data = models.ForeignKey('app1.A')

    def some_method(self):
        a_class = apps.get_model('app1', 'A')
        a_object = a_class.objects.get(id=1)
        ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question