Establishing One-to-Many Relationships in Flask-SQLAlchemy

Posted by


In Flask-SQLAlchemy, creating one-to-many relationships between tables involves using SQLAlchemy’s ORM (Object-Relational Mapping) system to define classes that represent database tables and their relationships. In this tutorial, we will cover how to set up a one-to-many relationship between two tables using Flask-SQLAlchemy.

First, ensure that you have Flask and Flask-SQLAlchemy installed in your project. You can install them using pip:

pip install Flask
pip install Flask-SQLAlchemy

Now, let’s create a simple Flask application with Flask-SQLAlchemy setup. Create a new Python file (app.py) and add the following code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db = SQLAlchemy(app)

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
    author = db.relationship('Author', backref='books')

if __name__ == '__main__':
    app.run(debug=True)

In this code, we have defined two models: Author and Book. The Author model represents authors, while the Book model represents books. The Book model has a foreign key column author_id that references the id column of the Author model.

The db.relationship function in the Book model defines the one-to-many relationship between authors and books. The backref='books' parameter specifies that each author object will have a books attribute that contains a list of books written by that author.

Now, let’s create the database tables using Flask-Migrate. Install Flask-Migrate with the following command:

pip install Flask-Migrate

Next, create a new Python file (manage.py) and add the following code:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

Now, run the following commands to set up the database migrations and create the initial migration:

python manage.py db init
python manage.py db migrate
python manage.py db upgrade

This will create a migrations folder in your project directory and create the necessary migration files based on your models.

Finally, let’s add some sample data to the database. Update app.py with the following code:

if __name__ == '__main__':
    app.run(debug=True)
    db.create_all()

    author1 = Author(name='John Doe')
    author2 = Author(name='Jane Doe')

    book1 = Book(title='Flask 101', author=author1)
    book2 = Book(title='SQLAlchemy Guide', author=author1)
    book3 = Book(title='Python Basics', author=author2)

    db.session.add(author1)
    db.session.add(author2)
    db.session.add(book1)
    db.session.add(book2)
    db.session.add(book3)
    db.session.commit()

Run the Flask application using python app.py command. This will create the database tables and add sample data to the database.

You can now access the data in the database and view the one-to-many relationship between authors and books. Use SQLAlchemy queries to retrieve data from the database:

from app import Author, Book

# get all authors
authors = Author.query.all()
for author in authors:
    print(author.name)
    for book in author.books:
        print(book.title)

This will print out the names of authors and titles of books written by each author, demonstrating the one-to-many relationship between authors and books.

Congratulations! You have created a one-to-many relationship between tables in Flask-SQLAlchemy. You can now build more complex relationships and queries using SQLAlchemy ORM.

0 0 votes
Article Rating

Leave a Reply

37 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@kaleabdemssie3844
1 hour ago

best explanation bro

@kaankako
1 hour ago

saved my 2 hours thank you

@ongayijohnian8787
1 hour ago

Could have been explained any better. Thanks a lot, best of luck G 💯

@surajpatil8670
1 hour ago

Great tutorial! Thank you

@RampageousRJ
1 hour ago

I am not able to see the foreign key in place using the GUI, am I doing something wrong?

@rezkyparma8795
1 hour ago

i have problem to search a text in serialized json in my table (let say i just want search by keyword then the keyword is contained in serialized json) , anybody have any thoughts bout this?

@oliveroshea5765
1 hour ago

Great video. The dog's name kept throwing me!!

@etutionlk
1 hour ago

Thanks anthony

@chrisgousset8673
1 hour ago

Awesome video thank you!

@pedroaragao6999
1 hour ago

Extremely helpful, thank you!

@robinbreed2439
1 hour ago

This is great, thank you.

@muskulanikhil3623
1 hour ago

fantastic

@edupailemilla
1 hour ago

hello thanks for the video! I have a question, in the sqlalchemy documentation it shows that its possible to insert Owner and Pet in the same commit. Can I do that with Flask-SQLalchemy? I've been trying, but it throws me an error, because the owner doesn't have an id when the insert operation starts.

@tylersnard
1 hour ago

FINALLY someone explains backref!

@LostMellodies
1 hour ago

Thank you so much man, you really helped me, I definitely gonna check out your course. Thanks again.

@sayhellotoroy
1 hour ago

That was helpful. Much easier to understand with those artificial fields

@NeutralGenericUser
1 hour ago

using deprecated backref in 2022. I feel bad for the people mislead by this video, which is nothing more than some lazy Googling. At least find up to date code smh.

@viniciusmelo984
1 hour ago

Excellent content!!

@gregalelov7993
1 hour ago

Great content :), really helped me.
Can you make some videos on sqlalchemy with FastAPI?

@emmanueladepoju4089
1 hour ago

Is this Bi-directional?

37
0
Would love your thoughts, please comment.x
()
x