- Phase: 9. Databases & Web Apps
- Duration: 2.5 hours
- Understand the ORM (object-relational mapping) concept
- Define database models with SQLAlchemy's declarative base
- Perform CRUD operations through the ORM
- Define relationships between models
- Query with filter and order_by
- ORM concept: mapping classes to database tables
- SQLAlchemy overview
- Declarative base (declarative_base)
- Defining models (Column, Integer, String, Float, DateTime, ForeignKey)
- Creating engine and session
- CRUD operations with ORM
- Relationships (relationship, back_populates)
- Querying with filter and order_by
Modules 000-083.
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
Base = declarative_base()
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
books = relationship('Book', back_populates='author')
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
author_id = Column(Integer, ForeignKey('authors.id'))
author = relationship('Author', back_populates='books')
engine = create_engine('sqlite:///library.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()- SQLAlchemy documentation: https://www.sqlalchemy.org
- SQLAlchemy ORM tutorial
- Flask-SQLAlchemy (for web integration)