DEV Community

dommieh97
dommieh97

Posted on

Demystifying SQLAlchemy: A Noob's Guide to Python's ORM

Introduction

If you're just getting started with database interactions in Python, the thought of dealing with SQL queries might seem daunting. Enter SQLAlchemy, a powerful Object-Relational Mapping (ORM) library that abstracts away the complexities of database management. In this noob-friendly guide, we'll take you on a tour of SQLAlchemy, unraveling its key concepts with simple examples. By the end of this 5-minute read, you'll have a solid grasp of how to use SQLAlchemy to interact with databases effortlessly.

Understanding SQLAlchemy

At its core, SQLAlchemy serves as a bridge between your Python code and a database. It allows you to work with database records as if they were Python objects, eliminating the need to write raw SQL queries. SQLAlchemy offers two main components: the Core and the ORM. In this guide, we'll focus on the ORM, which provides a higher-level abstraction and is great for noobs.

Setting Up

Before diving into examples, you'll need to install SQLAlchemy. Use the following command to install it using pip:

pip install sqlalchemy
Enter fullscreen mode Exit fullscreen mode

Basic CRUD Operations

Let's start with the basics: Create, Read, Update, and Delete operations. We'll use an example of a simple User model.

Alef. Creating Records:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

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

engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

new_user = User(name='Dommie')
session.add(new_user)
session.commit()
Enter fullscreen mode Exit fullscreen mode

Bet. Reading Records

all_users = session.query(User).all()
user = session.query(User).filter_by(name='Dommie').first()
Enter fullscreen mode Exit fullscreen mode

Gimel. Updating Records:

user.name = 'Dommie'
session.commit()
Enter fullscreen mode Exit fullscreen mode

Dalet. Deleting Records:

session.delete(user)
session.commit()
Enter fullscreen mode Exit fullscreen mode

Querying with Filters

SQLAlchemy makes querying a breeze. You can use filters to retrieve specific records.

# Retrieve users with names starting with 'D'
users_with_a = session.query(User).filter(User.name.like('D%')).all()

# Retrieve users with IDs in a given list
target_ids = [1, 3, 5]
target_users = session.query(User).filter(User.id.in_(target_ids)).all()
Enter fullscreen mode Exit fullscreen mode

Relationships

Databases often involve relationships between tables. SQLAlchemy simplifies this too.

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))

    author = relationship("User", back_populates="posts")

User.posts = relationship("Post", back_populates="author")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've taken your first steps into the world of SQLAlchemy. You've learned how to set up the library, perform basic CRUD operations, query records with filters, and establish relationships between tables. With this foundation, you can confidently build applications that interact with databases using Python. As you explore further, remember that SQLAlchemy offers even more advanced features to enhance your database interactions. Happy coding!

Top comments (0)