I have this error ImportError: cannot import name 'Maca' from partially initialized module 'maca.models' (most likely due to a circular import)
.
I have code like this
from maca.models import Maca
class Maca2(models.Model)
maca = models.ForeignKey(
Maca, on_delete=models.CASCADE
)
Now to model "Maca" I'm trying to access every single "Maca2" objects like this
from maca2.models import Maca2
class Maca(models.Model)
...
@property
maca_has_maca2(self)
maca2 = Maca2.objects.filter(maca=self.id)
Can you help me to handle this?
CodePudding user response:
You can import the Maca2
in the maca_has_maca2
property:
# no import of maca2.models
class Maca(models.Model):
# …
@property
def maca_has_maca2(self):
from maca2.models import Maca2
maca2 = Maca2.objects.all()
For ForeignKey
s, OneToOneField
s and ManyToManyField
s, you can make use of a string literal with as structure 'app_name.ModelName'
to refer to a model, for example:
# no import of maca2.models
class Maca(models.Model):
maca2 = models.ForeignKey(
'maca2.Maca2', on_delete=models.CASCADE
)
This avoids importing modules and thus circular imports. If the model has the same app_name
, you can reference this by 'ModelName'
.