[파이썬] SQLAlchemy JSON Field 활용

JSON (JavaScript Object Notation) has become a popular data format in recent years due to its simplicity and flexibility. It allows you to store structured data in a human-readable and lightweight format, making it easier for communication between different systems.

In this blog post, we will explore how to leverage the JSON field in SQLAlchemy, a popular Python SQL toolkit and Object-Relational Mapping (ORM) library, to store and query JSON data in a database.

Setting up SQLAlchemy

Before diving into the details, let’s make sure we have SQLAlchemy installed. You can install it using pip:

pip install sqlalchemy

Defining a JSON Field in SQLAlchemy

To use a JSON field in SQLAlchemy, we need to define a custom data type that supports JSON serialization and deserialization. SQLAlchemy provides the JSON type to handle JSON data.

from sqlalchemy import Column, Integer, String, JSON
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

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

In the above example, we have defined a User model with three columns - id, name, and data. The data column is of type JSON. It allows us to store JSON data in the database.

Storing JSON Data in the Database

To store JSON data in the database, we can simply assign a JSON object to the data field of the User model and commit the changes.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Create the engine
engine = create_engine('sqlite:///users.db')

# Create a session
Session = sessionmaker(bind=engine)
session = Session()

# Create a new user
user = User(name='John Doe', data={'age': 30, 'email': 'john.doe@example.com'})

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

# Commit the changes
session.commit()

In the above example, we create a new user object with a name and a JSON data field containing the user’s age and email. We then add the user to the session and commit the changes, which will persist the user data in the database.

Querying JSON Data

Once the JSON data is stored in the database, we can easily query it using SQLAlchemy.

# Retrieve all users
users = session.query(User).all()

# Access JSON data
for user in users:
    print(user.data['age'], user.data['email'])

In the example above, we retrieve all users from the database and access their JSON data using dot notation. We can access individual attributes of the JSON object just like any other column in the table.

Filtering JSON Data

Besides retrieving all users, we can also filter JSON data based on specific criteria. For example, to retrieve users who are above a certain age:

from sqlalchemy import func

# Retrieve users older than 25
older_users = session.query(User).filter(func.json_extract(User.data, '$.age') > 25).all()

In this example, we use json_extract function from SQLAlchemy’s func module to extract the age attribute from the JSON data. We then filter the users based on their age using the comparison operator >. The result will be a list of users who are older than 25.

Conclusion

By leveraging the JSON field in SQLAlchemy, we can seamlessly store and query JSON data in a relational database. It makes working with JSON data in a Python application more convenient and efficient.

In this blog post, we explored how to define a JSON field in SQLAlchemy, store JSON data in the database, and query the JSON data. We also demonstrated how to filter data based on specific criteria.

SQLAlchemy’s JSON field provides a powerful tool to work with JSON data in a relational database, opening up new possibilities for building flexible and scalable applications. Happy coding!