Rhythm Patel - No More Raw SQL: SQLAlchemy & ORMs | PyData London 2024

Learn how to improve database interactions with SQLAlchemy, a popular Python library for ORMs, and discover how to write more readable, maintainable, and efficient code with declarative mapping, lazy loading, and more.

Key takeaways
  • ORMs (Object-Relational Mappers) can improve code by reducing raw SQL queries and making it more readable and maintainable.
  • SQLAlchemy is a popular Python library that provides an ORM and simplifies database interactions.
  • The declarative_base class in SQLAlchemy can be used to create a base class for your ORM models.
    • This base class can then be used to create specific ORM models for each table.
  • SQLAlchemy provides features like lazy loading, eager loading, and cascading operations, which can simplify and optimize application logic.
  • Orm relationships (one-to-one, one-to-many, many-to-many) can be defined to simplify querying and reduce N+1 problems.
  • Declarative mapping allows you to map tables to classes and columns to properties.
  • SQLAlchemy supports various databases including SQLite, PostgreSQL, and DB2.
  • Composable queries can be built using SQLAlchemy’s expression language.
  • Session objects can be used to interact with the database and manage transactions.
  • Parameterized queries can prevent SQL injection attacks.
  • SQLAlchemy provides a default logging mechanism that can be used to log SQL queries.
  • Connection pooling can be used to maintain a pool of connections and improve application performance.