Python database libraries

Updated Nov 2026

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.

LibraryMonthly downloadsStarsLast releaseLicense
SQLAlchemy
413.8M
12.3KNov 2026MIT
Django ORM
51.9M
91.9KSep 2026BSD-3-Clause
Peewee
42.4M
12.0KOct 2026MIT
SQLModel
27.7M
18.6KNov 2026MIT
Pony ORM
855.0K
3.8KAug 2026Apache-2.0
Piccolo
696.7K
2.0KOct 2026MIT
Tortoise ORM
667.7K
5.6KOct 2026Apache-2.0
Ormar
123.9K
1.8KNov 2026MIT
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

Libraries and code examples

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.

Quickstart

From async_orm.py
$ pip install SQLAlchemy
from sqlalchemy import create_engine, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session

class Base(DeclarativeBase):
    pass
class Item(Base):
    __tablename__ = 'items'
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String())

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
with Session(engine) as session:
    session.add(Item(name='Hello'))
    session.commit()

SQLAlchemy examples

From open-source projects on GitHub

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.

Quickstart

From settings/
$ pip install Django
import django
from django.conf import settings

settings.configure(INSTALLED_APPS=[], DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}})
django.setup()
from django.db import connection, models

class Item(models.Model):
    name = models.CharField(max_length=100)
    class Meta:
        app_label = 'example'

with connection.schema_editor() as editor:
    editor.create_model(Item)
item = Item.objects.create(name='Hello')

Django ORM examples

From open-source projects on GitHub

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.

Quickstart

From quickstart.html
$ pip install peewee
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')

Peewee examples

From open-source projects on GitHub

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.

Quickstart

From create-db-and-table/
$ pip install sqlmodel
from sqlmodel import Field, Session, SQLModel, create_engine

class Item(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str

engine = create_engine('sqlite:///:memory:')
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
    session.add(Item(name='Hello'))
    session.commit()

SQLModel examples

From open-source projects on GitHub
def create_user(*, session: Session, user_create: UserCreate) -> User:
    db_obj = User.model_validate(
        user_create, update={"hashed_password": get_password_hash(user_create.password)}
    )
    session.add(db_obj)
    session.commit()
    session.refresh(db_obj)
    return db_obj

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.

Quickstart

From firststeps.html
$ pip install pony
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')

Pony ORM examples

From open-source projects on GitHub

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.

Quickstart

From table.py
$ pip install "piccolo[sqlite]"
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()

Piccolo examples

From open-source projects on GitHub
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 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.

Quickstart

From basic.py
$ pip install tortoise-orm
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())

Tortoise ORM examples

From open-source projects on GitHub

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.

Quickstart

From migrations/
$ pip install ormar aiosqlite
import asyncio
import ormar
import sqlalchemy

metadata = sqlalchemy.MetaData()
database = ormar.DatabaseConnection('sqlite+aiosqlite:///example.sqlite')
class Item(ormar.Model):
    ormar_config = ormar.OrmarConfig(tablename='items', database=database, metadata=metadata)
    id = ormar.Integer(primary_key=True)
    name = ormar.String(max_length=100)

metadata.create_all(sqlalchemy.create_engine('sqlite:///example.sqlite'))
async def main():
    async with database:
        await Item.objects.create(name='Hello')

asyncio.run(main())

Ormar examples

From open-source projects on GitHub

FAQ

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.

Run in your terminal

claude plugin install exa@claude-plugins-official