SQLAlchemy Fundamentals
Every SQLAlchemy application follows the same workflow.Database URL
Before connecting to a database, SQLAlchemy needs to know:- Which database to use
- Where it is located
- How to connect
General Format
The driver is optional. Specify it only when you want SQLAlchemy to use a particular driver.
URL Components
Common URLs
Dialect
A Dialect identifies the database type. Examples:Driver
A Driver is the Python library that communicates with the database.Engine
The Engine creates and manages database connections.- Opening connections
- Managing connection pooling
- Sending SQL to the database
DeclarativeBase
Before defining models, SQLAlchemy needs a place to register them.Base.
Base automatically registers every model.
Registry
The collection of registered models is called the Registry.Metadata
Metadata stores information about every registered model, including:- Table names
- Columns
- Primary keys
- Constraints
- Relationships
Session
The Session is SQLAlchemy’s workspace for communicating with the database. Every database operation goes through a Session.Creating a Session
Create a Session Factory.Git Analogy
Saving Changes
Start tracking a new object.Query Execution
Every query follows the same workflow.Build a Query
Execute the Query
Process the Result
Retrieving Results
Return all objects.None.
Why scalars()?
When a query is executed,
execute() returns a Result object, not the actual Student objects.
scalars().
scalars() returns a ScalarResult, which is an iterable of Student objects.
Why all()?
Use all() to convert the ScalarResult into a list.
all(), you can still iterate over the results.
Complete Flow
Key Points
execute()returns a Result object.scalars()extracts the ORM objects from the Result.scalars()returns a ScalarResult, not a list.all()converts theScalarResultinto a Python list.first(),one(), andone_or_none()retrieve objects in different ways.
get() is a shortcut for retrieving an object using its primary key.