Search code examples
pythonflaskmodelsqlalchemyflask-sqlalchemy

How do I reference multiple models in flask?


How do I handle and reference multiple models in a Flask application?

Is there any reason I cannot have more than one model class, .py files? Instead of one big models.py, is there a way to have the following in flask:

Example models:

students.py
teachers.py
classes.py
schedules.py
...

?


Solution

  • Yes, you can use multiple modules for your models. Nothing in Flask or Python limits you to a specific module name or to just one module.

    If you are using Flask-SQLAlchemy, just make sure you import the db object (the SQLAlchemy instance that defines the Model object) in each.

    When you want to use a model, simply import it from the right module:

    from students import Student
    # etc.
    

    If you are creating references between models, or want to use the create_all() function then at some point you'll need to have imported all models. Adding each module with a model to your main module would ensure this happens.