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)