Flask Database Modelling

Posted by

<!DOCTYPE html>

Database Modelling in Flask

Database Modelling in Flask

Flask is a popular web framework for Python that makes it easy to create web applications. One key aspect of building web applications is database modelling, which involves designing the structure of the database that will store and manage the data for the application.

In Flask, database modelling is typically done using an object-relational mapper (ORM) such as SQLAlchemy. SQLAlchemy provides a way to define database models using Python classes, making it easy to work with databases in Flask.

Creating Database Models

To create a database model in Flask, you need to define a class that represents a table in the database. Each attribute of the class corresponds to a column in the table, and each instance of the class represents a row in the table.

Here’s an example of a simple database model for a blog application in Flask:


from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    content = db.Column(db.Text)

In this example, we define a `Post` class that represents a table with columns for `id`, `title`, and `content`. The `db.Model` base class is used to indicate that `Post` is a database model, and the `db.Column` function is used to define the columns of the table.

Performing Database Operations

Once you have defined your database models, you can use SQLAlchemy to perform operations such as querying, inserting, updating, and deleting data in the database.

Here’s an example of how you might query all posts from the `Post` table in Flask:


posts = Post.query.all()

for post in posts:
    print(post.title)
    print(post.content)

Flask provides a powerful and flexible way to work with databases using SQLAlchemy. By defining database models in Flask, you can easily create, manage, and manipulate data in your web applications.