SQLAlchemy: How to Create a Table (Basic & Advanced)

Updated: January 3, 2024 By: Guest Contributor Post a comment

Introduction

SQLAlchemy, as a powerful ORM (Object-Relational Mapping) tool for Python, provides an effective way of handling database operations. In this tutorial, you’ll learn how to define and create tables in SQLAlchemy with detailed code examples, aiding you both at a beginner and an advanced level.

Getting Started with SQLAlchemy

Before diving into table creation, ensure that SQLAlchemy is installed in your Python environment. You can do this with the command:

pip install sqlalchemy

Once you have SQLAlchemy installed, you need to establish a connection to the database. With SQLAlchemy, the first step is creating an Engine instance which serves as the entry point to the database:

from sqlalchemy import create_engine
engine = create_engine('sqlite:///example.db')

Defining a Table Schema

In SQLAlchemy, you define a table schema using declarative base class:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)

This block of code defines a User model with ‘id’, ‘name’, and ‘fullname’ fields.

Creating the Table

To create the table in the database, you use the create_all method on the base class and pass the engine:

Base.metadata.create_all(engine)

Executing this code will generate the necessary SQL command to create a ‘users’ table.

Customizing Column Data Types and Constraints

To go a step further, you might want to apply specific data types or constraints to your columns:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)
    fullname = Column(String(50), unique=True)

Here, the ‘name’ column must contain data and the ‘fullname’ is unique.

Creating a Table with Relationships

Tables often have relationships with one another. SQLAlchemy eases the creation of foreign keys and table relationships:

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))

    user = relationship("User", back_populates="addresses")

User.addresses = relationship("Address", order_by=Address.id, back_populates="user")

This code snippet creates an ‘addresses’ table which has a ‘user_id’ foreign key pointing to the ‘id’ of a ‘users’ table. Furthermore, it establishes a relationship between both tables.

Handling Schema Migrations

In real-world applications, your schema will likely change over time. SQLAlchemy integrates with Alembic, a lightweight database migration tool, to handle such changes. After configuring Alembic, you can use migration scripts to modify your database schema safely.

Advanced SQLAlchemy Table Creation

For more complex scenarios, you may need to use events, custom data types, or non-traditional mappings offered by SQLAlchemy for advanced table creation.

from sqlalchemy.event import listen
def prepare_listener(target, value, oldvalue, initiator):
    # Custom logic before updating a record
    return value

listen(User.name, 'set', prepare_listener)

Listeners like the one above can be used to run code before or after certain events on your models.

Conclusion

Creating a table in SQLAlchemy is a clear process that involves defining your schema as a class and using the ORM’s built-in methods to carry out the database operations. Whether you need to define simple tables or handle complex relationships and migrations, SQLAlchemy, combined with tools such as Alembic, provides a rich toolkit to make database interactions in Python both efficient and robust.