I have semi-successfully split my large Flask app with a similar layout as follows. It all works as expected with one models.py file.
I'd also like to split the models into separate model files and that's where I am getting stuck. I'm using many to many relationships in the models.py file so:
- Created a models directory
- Split each SQLAlchemy class into it's own separate file importing db
The bit that seems to be breaking it is the many to many tables which was in the original model.py before the SQLAlchemy classes:
"""Data models."""
from .. import db
from datetime import datetime as dt
client_contact = db.Table('client_contact',
db.Column('client_id', db.Integer, db.ForeignKey('clients.id'), primary_key=True),
db.Column('contact_id', db.Integer, db.ForeignKey('contacts.id'), primary_key=True)
)
I get an error of:
contacts = db.relationship('Contact', secondary=client_contact, lazy='subquery', backref=db.backref('clients', lazy=True))
NameError: name 'client_contact' is not defined
I'm not sure how I can import the relationship piece of the jigsaw into each of the separate model files. This was the original structure and I followed the pallets application factory layout.
├── application
│ ├── admin
│ │ └── routes.py
│ ├── api
│ │ └── routes.py
│ ├── auth
│ ├── clientmanager
│ │ └── routes.py
│ ├── home
│ │ ├── routes.py
│ │ ├── static
│ │ └── templates
│ │ └── index.html
│ ├── __init__.py
│ ├── models.py
├── bin
├── config.py
├── include
├── lib
├── migrations
├── __pycache__
├── pyvenv.cfg
├── var
│ └── application-instance
│ └── pricing_insights.db
└── wsgi.py