0% found this document useful (0 votes)
6 views

Object-Relational Mapping (ORM) with Python

The document provides an overview of Object-Relational Mapping (ORM) with Python, highlighting its benefits such as code reusability, increased productivity, and data integrity. It discusses popular Python ORM libraries like SQLAlchemy and Django ORM, detailing their features and usage in web development, data analysis, and enterprise software. Additionally, it covers best practices for performance optimization and managing relationships in databases.

Uploaded by

inurture.su
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Object-Relational Mapping (ORM) with Python

The document provides an overview of Object-Relational Mapping (ORM) with Python, highlighting its benefits such as code reusability, increased productivity, and data integrity. It discusses popular Python ORM libraries like SQLAlchemy and Django ORM, detailing their features and usage in web development, data analysis, and enterprise software. Additionally, it covers best practices for performance optimization and managing relationships in databases.

Uploaded by

inurture.su
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Object-

Relational
Mapping
(ORM) with
Python
Outline

• Introduction to ORM

• Popular Python ORM Libraries

• Getting Started with


SQLAlchemy
• Working with Django ORM

• Best Practices and


Performance Optimization
Introduction to
ORM
Understanding the
Concept of ORM
Mapping Objects to Tables
ORM maps objects to tables and vice versa, providing a layer of
abstraction that simplifies database interaction and allows developers
to work with databases using object-oriented paradigms.

Object-Oriented Paradigms
ORM allows developers to work with databases using object-oriented
paradigms, such as encapsulation, inheritance, and polymorphism.

Abstraction Layer
ORM provides a layer of abstraction that simplifies database
interaction and reduces the amount of boilerplate code required,
making it easier and faster to develop database-driven applications.
Benefits of Using ORM

Code Reusability
ORM provides code reusability by abstracting database
interactions. Developers can reuse code across different projects,
reducing development time and effort.

Increased Productivity
ORM reduces the amount of code developers need to write,
allowing them to focus on business logic and other high-level
tasks. This increases productivity and speeds up development
time.

Data Consistency and Integrity


ORM provides type checking, validation, and other features that
ensure data consistency and integrity. This reduces the likelihood
of errors and ensures that data is accurate and reliable.
Common Use Cases and
Applications
Web Development
ORM is widely used in web development to simplify data modeling,
reduce boilerplate code, and make it easier to perform CRUD
operations. It is particularly useful in modern web frameworks, such
as Django and Rails.

Data Analysis
ORM can be used in data analysis to map database tables to Python
objects, making it easier to work with large databases and perform
data analysis tasks.

Enterprise Software
ORM is widely used in enterprise software to manage complex data
structures, simplify data access, and improve code maintainability.
Popular Python
ORM Libraries
SQLAlchemy: Features
and Usage
SQL Expression Language
SQLAlchemy provides a SQL expression language that allows developers
to write SQL statements in Python syntax, making it easier to work with
databases and write complex queries.

Object-Relational Mapper
SQLAlchemy provides a powerful and flexible Object-Relational Mapper
(ORM) that allows developers to map database objects to Python objects,
simplifying database interactions and reducing development time.

Schema Generator
SQLAlchemy provides a schema generator that allows developers to
create database schemas and tables programmatically using Python
code. This provides an efficient and flexible way to manage database
schema changes and versioning.
• Install: pip install sqlalchemy

• Setup Your Database:


For this example, we'll use SQLite, but SQLAlchemy supports various databases li
ke PostgreSQL, MySQL, etc.
• Import Required Modules:
• from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
• from sqlalchemy.ext.declarative import declarative_base
• from sqlalchemy.orm import sessionmaker, relationship

• Define the Database:


• engine = create_engine('sqlite:///example.db')
• Base = declarative_base()
Create Tables:
Base.metadata.create_all(engine)

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

Add Data:
new_user = User(name='John Doe', age=30)
new_address = Address(email='[email protected]', user=new_user)

session.add(new_user)
session.add(new_address)
session.commit()

Query the Database:


user = session.query(User).filter_by(name='John Doe').first()
print(f"User: {user.name}, Age: {user.age}")

for address in user.addresses:


print(f"Address: {address.email}")
• Create Models:
• Define two models: User and Address.

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

class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
email = Column(String)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", back_populates="addresses")
Django ORM: Automatic Table Creation
Django ORM provides automatic table creation, which
Features and simplifies the process of creating and modifying database

Usage tables and reduces the amount of boilerplate code required.

Powerful Query Syntax


Django ORM provides a powerful query syntax that allows
developers to easily and efficiently retrieve data from the
database. The syntax is flexible and supports complex queries,
making it particularly useful in web development.

Transactions and Migrations


Django ORM supports transactions and migrations, which
simplify the process of managing database changes and
ensure data consistency. Transactions ensure that multiple
database operations are executed as a single unit of work,
while migrations automate the process of modifying the
database schema.
Other Notable Python
ORM Libraries
Peewee
Peewee is a lightweight and easy-to-use ORM library that is designed
for small to medium-sized projects. It provides a simple and intuitive
API for interacting with databases.

Pony ORM
Pony ORM is a fast and expressive ORM library that provides a
Pythonic query syntax. It supports various popular databases,
including PostgreSQL, MySQL, SQLite, and Oracle.

Tortoise ORM
Tortoise ORM is an easy-to-use and scalable ORM library that supports
multiple databases. It provides an asynchronous API for faster
performance and supports various database systems like PostgreSQL,
MySQL, SQLite, and Oracle.
Getting Started
with
SQLAlchemy
Installation and
Setup
Install SQLAlchemy using pip
To install SQLAlchemy, use pip, the Python
package installer. It allows you to easily
manage and install Python packages and
dependencies.

Create a Database Connection


Once you have installed SQLAlchemy, you
can create a database connection by
specifying the database engine and
connection details. SQLAlchemy supports
multiple database engines, including
PostgreSQL, MySQL, SQLite, and Oracle.
Defining Models Defining Models in SQLAlchemy
In SQLAlchemy, you can define models as Python classes

and Schemas that inherit from a base class provided by SQLAlchemy.


Models are used to interact with the database tables in a
more object-oriented way.

Defining Schemas in SQLAlchemy


You can also define schemas in SQLAlchemy, which specify
the columns and data types for each table in the
database. Schemas help to organize the data and provide
a clear structure for the database tables.

SQL Expression Language in SQLAlchemy


SQLAlchemy provides a SQL expression language that
allows you to create complex queries using Python syntax.
This makes it easy to build complex queries and perform
database operations in a more efficient way.
Performing CRUD Create Operation
You can use the add() method in SQLAlchemy to perform
Operations create operation on the database using Python syntax.

Read Operation
You can use the filter() method in SQLAlchemy to perform read
operation on the database using Python syntax.

Update Operation
You can use the update() method in SQLAlchemy to perform
update operation on the database using Python syntax.

Delete Operation
You can use the delete() method in SQLAlchemy to perform
delete operation on the database using Python syntax.
Working with
Django ORM
Introductio
n to Django
Models

In Django ORM, models are


defined as Python classes
that inherit from a base class
provided by Django. Each
attribute of the model
represents a column in the
database table.
Querying the Database
with Django ORM
Django ORM Query Syntax
Django provides a powerful query syntax that allows you to perform
complex database queries using Python syntax. This makes it easy to
read and write queries in a language that you are already familiar
with.

Automatic SQL Query Generation


Django ORM generates the appropriate SQL for your queries behind
the scenes. This removes the need for you to manually write SQL
queries, which can be complex and error-prone.

Querying Related Objects


Django ORM supports querying related objects, such as foreign keys
and many-to-many relationships. This allows you to easily retrieve
related data without writing complex joins or subqueries.
Advanced Transactions
Django provides a transaction API that allows you to perform
Techniques and operations on the database in a transactional manner,

Custom Queries
ensuring data consistency and integrity.

Migrations
Django's migration framework allows you to manage changes
to your database schema over time, making it easy to track
and apply changes to your database.

Caching
Django provides a powerful caching framework that allows you
to store frequently accessed data in memory or on disk,
improving the performance of your application.

Custom Queries
Django ORM supports custom queries, which allow you to write
raw SQL and execute it using Django's database connection.
Custom queries are useful for writing complex queries that
cannot be expressed using Django's query syntax.
Best Practices
and
Performance
Optimization
Efficient Appropriate Data Types

Querying Using appropriate data types when creating tables in a database is crucial for
efficient querying and indexing. Choosing the right data type for a column
and Indexing ensures that the queries run fast and the indexes occupy less space.

Indexes on Frequently Queried Columns


Creating indexes on frequently queried columns is an effective way to
optimize queries. This reduces the query's response time and improves the
overall database performance.

Minimizing the Number of Queries


Minimizing the number of queries that are executed on a database is
important for performance optimization. Consolidating multiple queries into a
single query or caching the query results can greatly improve performance.

ORM Libraries Features


ORM libraries provide features for optimizing database queries such as lazy
loading and prefetching related objects. These features reduce the number of
queries executed on the database and improve the overall performance.
Managing
Relationships and
Foreign Keys
Importance of Managing Relationships
and Foreign Keys
Managing relationships and foreign keys is
important for maintaining data consistency
in databases. It ensures that data is accurate
and reduces the risk of data corruption.

ORM Libraries
ORM libraries provide features for managing
relationships and foreign keys, such as one-
to-one, one-to-many, and many-to-many
relationships. These features make it easier
to work with related data and reduce the
amount of boilerplate code required.
Dealing with Large
Datasets and Lazy
Loading
Lazy Loading
Lazy loading is a technique where related
objects are only loaded into memory when
they are accessed. This can be useful for
working with large datasets, as it reduces
memory usage and improves performance.

ORM Libraries
ORM libraries provide features for lazy
loading, such as lazy loading of related
objects and pagination. These features can
help manage large datasets and improve
performance.
Conclusion and Future
Trends

Emerging trends and technologies such as NoSQL databases and GraphQL suggest a
promising future for ORM in Python, making it easier to work with databases and achieve
higher levels of abstraction.

You might also like