DEV Community

Jessica Papa
Jessica Papa

Posted on

Getting Started with Creating a Database Table in Flask-SQLAlchemy

Flask-SQLAlchemy is a powerful tool that allows developers to seamlessly integrate a relational database into their Flask applications. Whether you're building a simple web app or a complex project, understanding how to create a database table using Flask-SQLAlchemy is a fundamental skill. In this beginner's guide, we'll walk you through the process step by step.

Prerequisites:

Before diving into creating a database table using Flask-SQLAlchemy, make sure you have the following set up:

Basic understanding of Python and Flask.

Flask and SQLAlchemy installed in your Python environment.
A database engine (like SQLite, MySQL, or PostgreSQL) configured for your Flask app.
Now, let's get started!

Step 1: Set Up Your Flask App:

Begin by creating a Flask application if you haven't already. Make sure to configure your app to use SQLAlchemy for database operations.

Here's a basic example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'  # Change this to your database URI
db = SQLAlchemy(app)
Enter fullscreen mode Exit fullscreen mode

Step 2: Define a Model:

In SQLAlchemy, a model represents a table in your database. Define a model class by creating a Python class that inherits from db.Model. Each attribute in the class will correspond to a column in the table. Here's an example of a simple 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}>'

Enter fullscreen mode Exit fullscreen mode

Step 3: Creating the Table:

Once you've defined your model, it's time to create the corresponding table in the database. To do this, open a Python shell or create a script and run the following commands:

from your_app_module import db, User

  • Update with your actual module and model names

  • Create the tables

db.create_all()

This will create the necessary table(s) based on your defined models.

Step 4: Interact with the Database:

With the table created, you can now interact with the database using your model. For example, to add a new user to the User table:

new_user = User(username='john_doe', email='john@example.com')
db.session.add(new_user)
db.session.commit()
Enter fullscreen mode Exit fullscreen mode

Step 5: Querying Data:

You can also perform queries on the table using SQLAlchemy's query API. Here's an example of how to retrieve all users:

all_users = User.query.all()
for user in all_users:
    print(user.username, user.email)
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Congratulations! You've successfully created a database table using Flask-SQLAlchemy and performed basic operations on it. This is just the beginning – Flask-SQLAlchemy offers many more advanced features for handling database relationships, migrations, and more.

As you continue to develop your Flask applications, you'll find that SQLAlchemy is a versatile and essential tool for working with databases.

Top comments (0)