0

Given the following Flask project structure, is it possible to import these models into each other without encountering a circular import error?

source
|-- __init__.py
|-- models
    |-- user.py
    |-- profile.py
    |-- posts.py

source/models/user.py:

from source.models.profile import Profile

class User(db.Model):
    ...

    profile = db.relationship(Profile.__name__, uselist=False, back_populates="user")

source/models/profile.py

from source.models.posts import Post
from source.models.user import User

class Profile(db.Model):
    ...

    user = db.relationship(User.__name__, back_populates="profile")

    posts = db.relationship(
        Post.__name__, uselist=False, back_populates="profile"
    )

source/models/posts.py

from source.models.profile.profile import Profile

class Post(db.Model):
    ...

    profile = db.relationship(Profile.__name__, back_populates="posts")

Example of error:

File "/app/source/models/posts.py" in <module> from source.models.profile import Profile
    ImportError: cannot import name 'Profile' from partially initialized module 
    'source.models.profile' (most likely due to a circular import) (/app/source/models/profile.py)
davidism
  • 121,510
  • 29
  • 395
  • 339
Guilherme
  • 35
  • 5
  • 1
    You can use the string name of the model instead – TheMonarch Feb 13 '23 at 14:32
  • 1
    Try `importlib` (see [example](https://stackoverflow.com/questions/10675054/how-to-import-a-module-in-python-with-importlib-import-module)). Or import the module file like [this](https://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python) – Wakeme UpNow Feb 13 '23 at 14:37

0 Answers0