Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python database libraries map database tables to Python classes, an approach called object-relational mapping (ORM), and build SQL from Python code. These libraries let web backends read and write table rows as Python objects instead of hand-written SQL.
Popularity
SQLAlchemy has the most monthly downloads in this comparison, at 413.8M.
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples
SQLAlchemy
SQLAlchemy is a SQL toolkit and object-relational mapper in two layers. Core is a SQL expression language with schema metadata, connection pooling, and type handling, usable on its own. The ORM is built on Core and synchronizes mapped Python objects with the current transaction through a Session. Queries written with the ORM reach joins, subqueries, and other SQL features through the object model, and eager loading fetches related objects with joins or one query per collection. Async code uses the same API through AsyncSession.
Downloads / mo
413.8M
Stars
12.3K
Last release
2.1.9
License
MIT
Strengths
Separates SQL expressions from objects.Use Core without adopting the ORM, or add mapped domain models.
Controls relationship loading.Choose eager-loading strategies for related objects and collections.
Limitations
Concurrent tasks need separate sessions.Give each thread or asyncio task its own session.
Schema diffs need manual review.Review and correct Alembic’s generated migration candidates before applying them.
def get_column_from_field(field: Any) -> Column:
field_info = field
sa_column = _get_sqlmodel_field_value(field_info, "sa_column", Undefined)
if isinstance(sa_column, Column):
return sa_column
sa_type = get_sqlalchemy_type(field)
primary_key = _get_sqlmodel_field_value(field_info, "primary_key", Undefined)
if primary_key is Undefined:
primary_key = False
index = _get_sqlmodel_field_value(field_info, "index", Undefined)
if index is Undefined:
index = False
nullable = not primary_key and is_field_noneable(field)
# Override derived nullability if the nullable property is set explicitly # on the field field_nullable = _get_sqlmodel_field_value(field_info, "nullable", Undefined)
if field_nullable is not Undefined:
assert not isinstance(field_nullable, UndefinedType)
nullable = field_nullable
args = []
foreign_key = _get_sqlmodel_field_value(field_info, "foreign_key", Undefined)
if foreign_key is Undefined:
foreign_key = None
unique = _get_sqlmodel_field_value(field_info, "unique", Undefined)
if unique is Undefined:
unique = False
if foreign_key:
ondelete_value = _get_sqlmodel_field_value(field_info, "ondelete", Undefined)
if ondelete_value is Undefined:
ondelete_value = None
if ondelete_value == "SET NULL" and not nullable:
raise RuntimeError('ondelete="SET NULL" requires nullable=True')
assert isinstance(foreign_key, str)
assert isinstance(ondelete_value, (str, type(None))) # for typing
args.append(ForeignKey(foreign_key, ondelete=ondelete_value))
kwargs: dict[str, Any] = {
"primary_key": primary_key,
"nullable": nullable,
"index": index,
"unique": unique,
}
sa_default = Undefined
if field_info.default_factory:
sa_default = field_info.default_factory
elif field_info.default is not Undefined:
sa_default = field_info.default
if sa_default is not Undefined:
kwargs["default"] = sa_default
sa_column_args = _get_sqlmodel_field_value(field_info, "sa_column_args", Undefined)
if sa_column_args is not Undefined:
args.extend(list(cast(Sequence[Any], sa_column_args)))
sa_column_kwargs = _get_sqlmodel_field_value(
field_info, "sa_column_kwargs", Undefined
)
if sa_column_kwargs is not Undefined:
kwargs.update(cast(dict[Any, Any], sa_column_kwargs))
return Column(*args, type_=sa_type, **kwargs)
Django ORM
Django ORM is the database layer of the Django web framework. Each model is a class that subclasses django.db.models.Model, each attribute maps to a column, and Django generates a database access API from the model. The ORM writes SQL tailored to the database backend named in the project settings. The makemigrations command records model changes as migration files, and migrate applies them. The ORM also provides asynchronous query methods, while transactions in async code run inside a synchronous function called through sync_to_async.
Downloads / mo
51.9M
Stars
91.9K
Last release
6.1.1
License
BSD-3-Clause
Strengths
Migrations included.makemigrations writes migrations from model changes, and migrate applies them.
Limitations
Transactions run synchronously.Async code wraps transactional ORM work in a synchronous function called through sync_to_async.
def create_line_discount_models(self, order, order_line, basket_line):
for discount in basket_line.discounts:
if not discount.offer:
continue
order_discount = order.discounts.filter(offer_id=discount.offer.id).first()
# If we are unable to find the discount we do not care, the total amount is still saved on the discount model, # these models are only created so we know how much discount was given per line for each offer if order_discount:
order_line.discounts.create(
order_discount=order_discount,
is_incl_tax=discount.incl_tax,
amount=discount.amount,
)
Peewee
Peewee is a small ORM in a single module with no required dependencies. SQLite works through the standard library, and extras such as peewee[postgres] and peewee[mysql] install drivers for other databases, including async drivers. Models subclass Model and point at a database such as SqliteDatabase, and a query builder exposes joins and other SQL features. The pwmigrate command generates schema migrations from a diff of the models.
Downloads / mo
42.4M
Stars
12.0K
Last release
4.5.3
License
MIT
Strengths
Keeps the core dependency-light.Use the single-module ORM with SQLite before adding backend-specific drivers.
Includes migrations and async drivers.Use the included migration runner and asyncio integrations for supported databases.
Limitations
Renamed fields look like replacements.Replace generated add/drop pairs with rename operations when existing data must survive.
Pooled connections must be released.Close each request’s connection or use a context manager to return it.
from peewee import Model, SqliteDatabase, TextField
db = SqliteDatabase(':memory:')
class Item(Model):
name = TextField()
class Meta:
database = db
Item.create_table()
item = Item.create(name='Hello')
@router.get(
"/event_ids",
response_model=list[EventResponse],
dependencies=[Depends(allow_any_authenticated())],
summary="Get events by ids",
description="""Gets events by a list of ids.
Returns a list of events.
""",
)
async def event_ids(ids: str, request: Request):
ids = ids.split(",")
if not ids:
return JSONResponse(
content=({"success": False, "message": "Valid list of ids must be sent"}),
status_code=400,
)
try:
events = list(Event.select().where(Event.id << ids).dicts().iterator())
except Exception:
return JSONResponse(
content=({"success": False, "message": "Events not found"}), status_code=400
)
for event in events:
await require_camera_access(event["camera"], request=request)
return JSONResponse(events)
SQLModel
SQLModel defines database tables as Python classes with type annotations, built on Pydantic and SQLAlchemy. A class declared with table=True is both a Pydantic model that validates data and a SQLAlchemy table. Queries run through a SQLAlchemy engine and session, and SQLModel.metadata.create_all creates the tables. The same author wrote FastAPI, and SQLModel models work as request and response types in FastAPI routes.
Downloads / mo
27.7M
Stars
18.6K
Last release
0.0.50
License
MIT
Strengths
One model, two roles.A single class works as the Pydantic model and the SQLAlchemy table.
Pony ORM writes database queries as Python generator expressions and lambdas, such as select(p for p in Product if p.name.startswith('A')). Pony reads the abstract syntax tree of the expression and translates it into SQL for the database dialect in use, with support for SQLite, MySQL, PostgreSQL, and Oracle. Entities are declared as compact classes, and the generated SQL can be printed in a readable, indented form. An online diagram editor generates a schema from an entity relationship diagram.
Downloads / mo
855.0K
Stars
3.8K
Last release
0.7.20
License
Apache-2.0
Strengths
Writes queries as Python expressions.Use generator expressions and lambdas that translate into SQL.
Manages transaction and identity state.Commit or roll back and return connections when a database session ends.
Limitations
Lazy attributes need live sessions.Load required attributes before leaving the database session.
Nested sessions share one transaction.An inner rollback also rolls back the outer session.
from pony.orm import Database, Required, db_session
db = Database()
class Item(db.Entity):
name = Required(str)
db.bind(provider='sqlite', filename=':memory:')
db.generate_mapping(create_tables=True)
with db_session:
item = Item(name='Hello')
@db_session
def query_with_augmenter(self, query: str, augmenter: AugmentedSearch, first: int = 1, last: int = 50,
sort_desc: bool = True, sort_by: str = "") -> list[TorrentMetadata]:
"""
Use the given augmenter to perform a heavier search for the given query.
:returns: A Query object that evaluates to a list of TorrentMetadata.
"""
limit, offset = max(1, last - first), max(1, first)
results = [r[0] for r in self.db.get_connection().execute(*augmenter.augment(query, limit, offset)).fetchall()]
pony_query = select(g for g in cast("TorrentMetadata", self.TorrentMetadata) if g.rowid in results)
return cast("list[TorrentMetadata]", self.apply_sort_by_option(pony_query, sort_by, sort_desc))
Piccolo
Piccolo is an ORM and query builder that supports both synchronous and asyncio code. Tables are classes, and queries either chain methods such as select and where or work on objects through objects, save, and remove. The package includes a User model, authentication, migrations, and a playground for trying queries. The piccolo asgi new command creates a starter web app for frameworks such as Starlette, FastAPI, and Litestar, and Piccolo Admin adds an admin interface on top.
Downloads / mo
696.7K
Stars
2.0K
Last release
1.39.0
License
MIT
Strengths
Migrations and admin included.The package ships a User model, authentication, migrations, and an admin GUI.
from piccolo.table import Table
from piccolo.columns import Varchar
from piccolo.engine.sqlite import SQLiteEngine
class Item(Table, db=SQLiteEngine(path='example.sqlite')):
name = Varchar()
Item.create_table(if_not_exists=True).run_sync()
def create_schema(persist: bool = False):
if not persist:
drop_db_tables_sync(*TABLE_CLASSES)
create_db_tables_sync(*TABLE_CLASSES, if_not_exists=True)
Tortoise ORM
Tortoise ORM is an asyncio ORM with a model and query API modeled on Django. Every database call is awaited, and the library supports SQLite, MySQL, PostgreSQL, Microsoft SQL Server, and Oracle through separately installed database clients. Models declare fields and relationships as class attributes. The tortoise command line tool detects model changes, writes migration files with makemigrations, and applies them with migrate.
Downloads / mo
667.7K
Stars
5.6K
Last release
1.1.9
License
Apache-2.0
Strengths
Uses an async-native model API.Await database operations through a Django-inspired model and query interface.
Includes versioned schema migrations.Detect model changes and apply generated migrations through the included CLI.
Limitations
Nested transactions must stay sequential.Avoid nesting transaction blocks inside concurrent tasks sharing an outer transaction.
Data migrations need historical models.Load migration models through apps.get_model instead of importing current runtime classes.
from tortoise import fields, run_async
from tortoise.models import Model
from tortoise.contrib.test import init_memory_sqlite
class Item(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
@init_memory_sqlite
async def main():
item = await Item.create(name='Hello')
print(item.id)
run_async(main())
async def _do_init(self, safe: bool, pre_sql: str | None = None, offline: bool = False) -> bool:
"""Initialize the database for an app.
Returns True if a new initial migration was generated, or False when existing migration
files were found and applied to a fresh database (e.g. a cloned repository).
Raises FileExistsError when the database is already initialized.
"""
location = self.location
app = self.app
config = self.tortoise_config
await Tortoise.init(config=config)
connection = get_app_connection(config, app)
if offline:
await Migrate.init(config, app, location, offline=True)
elif pre_sql:
await connection.execute_script(pre_sql)
dirname = Migrate.get_migration_dir(location, app)
if not dirname.exists():
dirname.mkdir(parents=True)
else:
existing_version_files = [
f for f in dirname.glob("*.py") if "_" in f.stem and f.stem.split("_")[0].isdigit()
]
if existing_version_files and not offline:
# Migration files already exist. Check whether the database has been # initialised by querying the aerich tracking table. try:
already_initialized = await Aerich.exists(app=app)
except OperationalError:
already_initialized = False
if already_initialized:
raise FileExistsError(str(existing_version_files[0]))
# Fresh database with existing migration files (e.g. a repo that was cloned). # Apply all migrations in order so the database reaches the current state. Migrate.app = app
Migrate.migrate_location = dirname
app_conn_name = get_app_connection_name(config, app)
for version_module in Migrate.get_all_version_modules():
version_file = version_module.name + ".py"
m = import_py_module(version_module)
if getattr(m, "RUN_IN_TRANSACTION", True):
async with in_transaction(app_conn_name) as conn:
await self._upgrade(conn, version_file, version_module=version_module)
else:
await self._upgrade(connection, version_file, version_module=version_module)
return False
# Directory is empty (or offline mode with existing files): raise for any present file. for unexpected_file in dirname.glob("*"):
raise FileExistsError(str(unexpected_file))
schema = get_schema_sql(connection, safe)
version = await Migrate.generate_version(offline=offline)
aerich_content = get_models_describe(app)
version_path = Path(dirname, version)
content = Migrate.build_migration_file_text(upgrade_sql=schema, models_state=aerich_content)
version_path.write_text(content, encoding="utf-8")
Migrate._last_version_content = aerich_content
if not offline:
await generate_schema_for_client(connection, safe)
await Aerich.create(version=version, app=app, content=aerich_content)
return True
Ormar
Ormar is an async ORM for PostgreSQL, MySQL, and SQLite whose models are also Pydantic models. A single class therefore validates data and maps a table, and FastAPI can use it directly as a request and response model. SQLAlchemy Core builds the queries, column types, and connection pool underneath. Async drivers such as asyncpg and aiosqlite run the queries, and schema migrations go through Alembic.
Downloads / mo
123.9K
Stars
1.8K
Last release
0.30.0
License
MIT
Strengths
Pydantic models as tables.Each model validates data with Pydantic and maps a table.
Limitations
Migrations through Alembic.Tables are based on SQLAlchemy, so schema migrations run through Alembic.
SQLAlchemy covers both raw SQL expressions and mapped models. Django ORM comes with a Django project, SQLModel shares Pydantic models with FastAPI, and Tortoise ORM and Piccolo are written around asyncio. Peewee is a single module with no required dependencies.
SQLModel is a thin layer on SQLAlchemy and Pydantic. Each model is both a table and a validated data class. SQLAlchemy used directly exposes its full Core and ORM, which SQLModel also allows underneath.
Yes. SQLAlchemy runs ORM queries through AsyncSession with an async database driver. Each concurrent task needs its own AsyncSession.
Django ORM is part of the Django framework and reads its database settings from the project. SQLAlchemy is a standalone library used with any framework, with a separate SQL expression layer and Alembic for migrations.
Peewee is a single module with no required dependencies and includes a migration tool, pwmigrate. SQLAlchemy has a larger API, with a separate Core layer, configurable relationship loading, and migrations through Alembic.
Django ships makemigrations and migrate, Tortoise ORM has its own migration CLI, Peewee generates migrations with pwmigrate, and Piccolo includes migrations. SQLAlchemy, SQLModel, and Ormar use Alembic.
For coding agents
Found your database library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.