Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crossed import in django

On example, i have 2 apps: alpha and beta in alpha/models.py import of model from beta.models and in beta/models.py import of model from alpha.models

manage.py validate says that ImportError: cannot import name ModelName

how to solve this problem?

like image 607
Kuhtraphalji Avatar asked Feb 27 '23 22:02

Kuhtraphalji


1 Answers

I have had this issue in the past there are two models that refer to one another, i.e. using a ForeignKey field. There is a simple way to deal with it, per the Django documentation:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

So in your beta/models.py model, you would have this:

class BetaModel(models.Model):
    alpha = models.ForeignKey('alpha.AlphaModel')
    ...

At this point, importing from alpha.models is not necessary.

like image 78
AdmiralNemo Avatar answered Mar 06 '23 02:03

AdmiralNemo