ORM Concepts in Python 🎯

beginner
15 min

ORM Concepts in Python 🎯

Welcome to the ORM (Object-Relational Mapping) tutorial! In this lesson, we'll dive deep into the world of ORM, exploring how it helps developers interact with databases in a more Pythonic and efficient way.

What is ORM? 📝

ORM is a technique that allows us to interact with databases using objects, instead of writing raw SQL queries. It simplifies database access and makes the code more maintainable, readable, and portable.

Why Use ORM? ✅

  • Ease of use: ORM abstracts away the complexity of writing SQL queries, making it easier for developers, especially beginners, to interact with databases.
  • Productivity boost: ORM saves time by automating the mapping between database tables and Python classes, reducing the need to write repetitive SQL code.
  • Portability: Since ORM abstracts database access, it makes it easier to switch databases without having to change the application logic.

Popular ORMs in Python 💡

  1. SQLAlchemy: A powerful and flexible ORM that supports multiple databases and is widely used in larger projects.
  2. Django ORM: A built-in ORM in Django, a popular web framework, offering an easy-to-use interface for database interactions.

Getting Started with SQLAlchemy 🎯

Let's start by installing SQLAlchemy:

bash
pip install sqlalchemy

Creating a Database Model 📝

python
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///example.db') Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String)

In the above example, we create a User class representing a users table in the database. The __tablename__ attribute specifies the name of the table, while Column is used to define the columns with their data types.

Saving Data to the Database 🎯

python
# Creating a session from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() # Creating a new user user = User(name='John', email='john@example.com') session.add(user) session.commit()

In this example, we create a session, add a new user, and commit the transaction to the database.

Querying Data 🎯

python
# Fetching all users users = session.query(User).all() for user in users: print(f'Name: {user.name}, Email: {user.email}')

In this example, we fetch all users from the database and print their names and emails.

Quiz 📝

Quick Quiz
Question 1 of 1

What is the purpose of ORM in Python?


Stay tuned for more advanced examples and tips on using ORM effectively in your projects! 🎉