0

I have declared models which requires the use of database relationships in modules of both models leading to a "Cannot import name Region" error. To better illustrate this, here is my sample models

project/location/models.py

from project.location.models import Region

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(175), unique=True, nullable=False)
    region = db.Column(db.Integer, db.ForeignKey('regions.id'))
    regions = db.relationship(Region, backref='projects')

from the next module,
project/deliverables/models

from project.deliverables.models import Project

class Region(db.Model):
    name = db.Column(db.String(30))
    id = db.Column(db.Integer, primary_key=True)
    projects = db.relationship("Project", backref='regions')

How best can I avoid circular import so future models declaration will not be entangled in this phenomena ?

afidegnum
  • 161
  • 4
  • 21
  • So, a Project is in a Region? I don't understand why a Region would hold a reference to a Project. – OneCricketeer Feb 11 '16 at 15:39
  • they both use db.relationship on a related models, Project.region.name and Region.project.names. A content with the regions they belong to. and Select Projects from specific regions. – afidegnum Feb 11 '16 at 15:44
  • You have your import statements switched. `from project.location.models import Region` should be `from project.deliverables.models import Region`, right? Same for the other one – OneCricketeer Feb 11 '16 at 15:47
  • Other than that - Maybe see this post - http://stackoverflow.com/questions/15547156/circular-dependency-in-models-with-sqlalchemy – OneCricketeer Feb 11 '16 at 15:50
  • 1
    @cricket_007's link is the answer but just to make it explicit, define the relationship with a string so you don't need to import anything `db.relationship('Region', backref='projects')`. – tdelaney Feb 11 '16 at 16:24
  • @tdelaney, i did that but when initiating the db migration, I do have error. – afidegnum Feb 11 '16 at 16:48
  • You'll want to have the files not import each other. The key is to use strings and **not attempt to import the names**. Import `Region` inside `location/models.py`, don't import `Project` inside `deliverables/models.py`, and use `"Project"` to set up the `projects` relationship. If you're already doing that, you'll need to post what error message you're getting. – univerio Feb 11 '16 at 19:57

1 Answers1

0

I made it work, in this case, I had to Quote the model names instead of using their variables.

afidegnum
  • 161
  • 4
  • 21