[파이썬] SQLAlchemy Multiple Foreign Key Constraints

When working with relational databases, it is common to have tables with multiple foreign key constraints. SQLAlchemy, a popular Python library for working with databases, provides an elegant and powerful way to define multiple foreign key constraints on your table schema.

In this blog post, we will explore how to define and work with multiple foreign key constraints using SQLAlchemy in Python.

Setting up the Environment

Before we begin, make sure you have SQLAlchemy installed. You can install it using pip:

pip install sqlalchemy

Also, let’s assume that we have a database with two tables, users and roles, where each user can have multiple roles. We will create a relationship between these two tables using multiple foreign key constraints.

Defining the Tables

To define the relationship between the users and roles tables, we need to create the table schemas using SQLAlchemy. Below is an example of how to define the tables:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    roles = relationship("Role", back_populates="user")

class Role(Base):
    __tablename__ = 'roles'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship("User", back_populates="roles")

In the above code, we define two classes User and Role, representing the users and roles tables, respectively. The user_id column in the roles table is defined as a foreign key referencing the id column in the users table.

To establish the relationship between these two tables, we use the relationship function. In the User class, we define the relationship with the Role class as roles. Similarly, in the Role class, we define the relationship with the User class as user.

Working with Multiple Foreign Key Constraints

Once we have defined the tables and their relationship, we can perform various operations on them, such as inserting, updating, and querying data. Here are a few examples:

Inserting Data

To insert data into the tables, we can create instances of the User and Role classes and add them to the session:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Create an engine and a session
engine = create_engine('sqlite:///database.db')
Session = sessionmaker(bind=engine)
session = Session()

# Create user and role instances
user = User(name='John Doe')
role = Role(name='Admin', user=user)

# Add instances to the session
session.add(user)
session.add(role)

# Commit the changes
session.commit()

Querying Data

To query data from the tables, we can use the session and the predefined relationships:

# Query all users and their roles
users = session.query(User).all()
for user in users:
    print(f'User: {user.name}')
    for role in user.roles:
        print(f'Role: {role.name}')

# Query all roles and their associated users
roles = session.query(Role).all()
for role in roles:
    print(f'Role: {role.name}')
    print(f'User: {role.user.name}')

Updating Data

To update data in the tables, we can modify the attributes of the instances and commit the changes:

# Update the name of a user
user.name = 'Jane Doe'
session.commit()

Conclusion

In this blog post, we have learned how to define and work with multiple foreign key constraints using SQLAlchemy in Python. By using the relationship function, we can establish relationships between tables and perform various operations on them.

SQLAlchemy provides an easy-to-use and intuitive API for working with databases, making it a popular choice among Python developers. Whether you are working on small projects or large enterprise applications, SQLAlchemy can help you effectively manage multiple foreign key constraints in your database schemas.