Module 8: Database Interaction

Working with SQL and NoSQL databases effectively.

8.1 SQLAlchemy ORM

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

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

Base = declarative_base()

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

8.2 Django ORM

Django's built-in ORM is powerful and easy to use, abstracting away much of the SQL complexity.

8.3 Raw SQL & Migrations

When to use raw SQL for performance. Managing database schema changes using tools like Alembic (for SQLAlchemy) or Django Migrations.

8.4 NoSQL with Python

Interacting with NoSQL databases like MongoDB (using PyMongo or Motor) and Redis.

🎯 Practical Exercise

Create a simple data model using SQLAlchemy, generate a migration script using Alembic, and apply it to a SQLite database.