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?