0

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
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
  • Does this answer your question? [SQLAlchemy classes across files](https://stackoverflow.com/questions/7478403/sqlalchemy-classes-across-files) – pjcunningham Oct 13 '22 at 09:05
  • Nope not that I can see, the previous question is about breaking a models.py into model1.py, model2.py etc which I have already done. My issue is specifically with Flask SQLAlchemy and many to many relationships. – Johnny John Boy Oct 13 '22 at 12:48
  • If you could not mark it as duplicate that would be great as it's not. – Johnny John Boy Oct 13 '22 at 12:50

0 Answers0