Flask SqlAlchemy ORM


What is Flask-SQLAlchemy?

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy, a powerful Object Relational Mapping (ORM) library for working with databases. It allows you to define models (Python classes) and map them to database tables, making it easier to interact with the database using Python objects rather than writing raw SQL queries.


How do you install and configure Flask-SQLAlchemy?

To install Flask-SQLAlchemy, you can use the pip package manager. After installation, you need to configure your Flask app to connect to the database by setting the SQLALCHEMY_DATABASE_URI configuration variable.

Steps to install and configure:

pip install Flask-SQLAlchemy

In the Flask app:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

In this example, Flask-SQLAlchemy is installed and configured to use an SQLite database. The SQLALCHEMY_DATABASE_URI points to the database file, and the db object is initialized with the Flask app.


How do you define a model in Flask-SQLAlchemy?

In Flask-SQLAlchemy, a model is defined as a Python class that inherits from db.Model. Each class attribute corresponds to a column in the database table, and each instance of the class represents a row in the table.

Example of defining a model:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

In this example, the User model defines three columns: id, username, and email. The id is the primary key, and both username and email are unique and cannot be null.


How do you create the database tables from models in Flask-SQLAlchemy?

Once you have defined your models, you can create the corresponding database tables by using the db.create_all() method. This will create the necessary tables based on the models defined in your application.

Example of creating tables:

with app.app_context():
    db.create_all()

In this example, db.create_all() is called inside the application context to create the tables for all the defined models in the database.


How do you add data to the database using Flask-SQLAlchemy?

To add data to the database, you create an instance of the model and add it to the session using db.session.add(), followed by db.session.commit() to save the changes to the database.

Example of adding a new user:

new_user = User(username='john', email='[email protected]')
db.session.add(new_user)
db.session.commit()

In this example, a new user is created with the username "john" and email "[email protected]", added to the session, and then committed to the database.


How do you query data from the database using Flask-SQLAlchemy?

Flask-SQLAlchemy provides various methods for querying data from the database. The most common method is query, which allows you to filter, sort, and retrieve data from the database.

Example of querying all users:

users = User.query.all()

Example of querying a single user by username:

user = User.query.filter_by(username='john').first()

In these examples, query.all() retrieves all users from the database, and query.filter_by() retrieves a user with the username "john".


How do you update data in the database using Flask-SQLAlchemy?

To update data in the database, you first query the record you want to update, modify the attributes, and then commit the changes using db.session.commit().

Example of updating a user's email:

user = User.query.filter_by(username='john').first()
user.email = '[email protected]'
db.session.commit()

In this example, the user's email is updated, and the changes are committed to the database.


How do you delete data from the database using Flask-SQLAlchemy?

To delete data from the database, you query the record, delete it using db.session.delete(), and then commit the changes using db.session.commit().

Example of deleting a user:

user = User.query.filter_by(username='john').first()
db.session.delete(user)
db.session.commit()

In this example, the user with the username "john" is deleted from the database, and the change is committed.


How do you define relationships between models in Flask-SQLAlchemy?

Flask-SQLAlchemy supports defining relationships between models using foreign keys and relationships. You can use the db.ForeignKey and db.relationship methods to define one-to-many, many-to-many, and one-to-one relationships between models.

Example of a one-to-many relationship:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    user = db.relationship('User', backref=db.backref('posts', lazy=True))

In this example, the Post model has a foreign key user_id that references the id column of the User model. The db.relationship function establishes the relationship between User and Post, allowing you to access a user's posts.


How do you define one-to-one relationships in Flask-SQLAlchemy?

One-to-one relationships in Flask-SQLAlchemy are defined similarly to one-to-many relationships, but you can add the uselist=False argument to ensure that only one related object is allowed.

Example of a one-to-one relationship:

class Profile(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    bio = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('profile', uselist=False))

In this example, each User can have only one Profile, and the uselist=False ensures that the relationship is one-to-one.


How do you define many-to-many relationships in Flask-SQLAlchemy?

Many-to-many relationships in Flask-SQLAlchemy are created using an association table that holds foreign keys to both related tables. This table acts as a bridge between the two models.

Example of a many-to-many relationship:

tags = db.Table('tags',
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True),
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True)
)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    tags = db.relationship('Tag', secondary=tags, backref=db.backref('posts', lazy=True))

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)

In this example, an association table called tags is created to hold the relationships between Post and Tag. Each post can have multiple tags, and each tag can be associated with multiple posts.


How do you perform database migrations with Flask-SQLAlchemy?

Database migrations allow you to manage changes to your database schema over time without losing data. Flask-SQLAlchemy integrates with the Flask-Migrate extension to provide database migrations. You define models as usual, and Flask-Migrate generates the necessary SQL commands to alter the database schema.

To set up migrations:

pip install Flask-Migrate

In your Flask app:

from flask_migrate import Migrate

migrate = Migrate(app, db)

Example of using migration commands:

flask db init     # Initialize migrations folder
flask db migrate  # Generate migration scripts
flask db upgrade  # Apply migrations to the database

In this example, Flask-Migrate is set up to manage database migrations, and the migration commands are used to create and apply migrations.

Ads