2

I'm using Flask-SQLAlchemy with blueprints, in a setup based on cookiecutter-flask, which gets around most circular import problems.

However, my situation is the following. I have two related (actually, it probably doesn't matter if have a database relationship between them or not) models/tables that are declared in different Python modules. I would like to extend both models with custom methods that query the other model. Minimal example:

# employee/models.py
class Employee(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    company_id = db.Column(db.ForeignKey('company.id'))
    company = db.relationship("Company", backref="employees") # Referencing "Company" as str avoids circular import

    def job_opportunities(self):
        # Complicated query based on this employee's data
        return Company.query.filter(...).all()

and

# company/models.py
class Company(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))

    def potential_new_employees(self):
        # Complicated query bsaed on this company's data
        return Employee.query.filter(...).all()

Both files have a method which needs to import the model defined in the other module. I would like to keep both models separated in different modules. What is a clean pattern to solve this problem?

Mark
  • 1,306
  • 13
  • 19

1 Answers1

1

I'm not sure if this is the correct way, but after hours of struggling with the same issue I found a workaround: just put your model import into a method where you need to use it.

    def potential_new_employees(self):
        from models.employee import Employee
        # Complicated query bsaed on this company's data
        return Employee.query.filter(...).all()

Also if you have already found another working solution I would be grateful for sharing.

greenwd
  • 135
  • 1
  • 10