SQLAlchemy & ORM

SQLAlchemy & ORM in Python: Writing raw SQL strings ( ) is fine for small scripts, but in large apps, it's hard to maintain.

Concept Explanation

Writing raw SQL strings ("SELECT * FROM users...") is fine for small scripts, but in large apps, it's hard to maintain.

  • What if you spell a table name wrong?
  • What if you switch from SQLite to PostgreSQL? You'd have to rewrite all your code.

SQLAlchemy is an Object-Relational Mapper (ORM). It allows you to interact with your database using pure Python classes and objects. You never have to write a single line of SQL if you don't want to. It acts as a translator between your Python code and the database.


Syntax or Core Structure

The Three Layers

  1. Engine: The connection to the database.
  2. Declarative Base: A base class that your "Models" (tables) inherit from.
  3. Session: The workspace where you perform operations.
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker

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

# 2. Create Base
Base = declarative_base()

# 3. Define a Model (Table)
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)

# 4. Create Tables
Base.metadata.create_all(engine)

Code Example #1 (Basic)

Adding and querying data using Sessions.

from sqlalchemy.orm import sessionmaker

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

# 1. Create a New User object
new_user = User(name="Alice", email="alice@example.com")

# 2. Add and Commit
session.add(new_user)
session.commit()

# 3. Query
found_user = session.query(User).filter_by(name="Alice").first()
print(f"Found ID: {found_user.id}")

session.close()

Code Example #2 (Intermediate)

Relationships between tables (One-to-Many).

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    
    # Connect User to many posts
    posts = relationship("Post", back_populates="author")

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")

Real World Example

Blog Engine Backend: Handling authors and their blog posts programmatically.

# To get all posts by a specific user:
user = session.query(User).filter_by(name="Alice").first()
for post in user.posts:
    print(f"Post Title: {post.title}")

Common Mistakes

  1. Forgetting session.commit(): Just like standard SQLite, your changes won't be saved until you commit the session.
  2. Naming Collisions: Naming your model class User while another library also has a class called User. Always use descriptive names.
  3. Lazy Loading Performance: If you have 100 users and each has 100 posts, looping through them might trigger 10,000 separate database queries. Look up .joinedload() to fix this.

Best Practices

  • Use Alembic for Migrations: If you change your table structure (e.g., add an "Age" column), don't delete your database. Use a migration tool like Alembic.
  • Environment Variables for URLs: Store your database URL (sqlite:///db.db) in a .env file so you can easily switch to a production database later.
  • Sessions as Context Managers: Use with Session() as session: to ensure sessions are always closed.

Practice Exercises

  1. The Library System: Create two models: Author and Book. Link them together so one Author can have many Books.
  2. The Data Searcher: Create a script that finds all Users whose email contains "@gmail.com" using the .filter() and .like() methods.
  3. The Bulk Inserter: Create a list of 10 dictionary items and use session.add_all() to insert them into your database in one go.