# Python database libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [SQLAlchemy](#sqlalchemy) | 413.8M | 12.3K | Nov 2026 | MIT |
| [Django ORM](#django) | 51.9M | 91.9K | Sep 2026 | BSD-3-Clause |
| [Peewee](#peewee) | 42.4M | 12.0K | Oct 2026 | MIT |
| [SQLModel](#sqlmodel) | 27.7M | 18.6K | Nov 2026 | MIT |
| [Pony ORM](#pony-orm) | 855.0K | 3.8K | Aug 2026 | Apache-2.0 |
| [Piccolo](#piccolo) | 696.7K | 2.0K | Oct 2026 | MIT |
| [Tortoise ORM](#tortoise-orm) | 667.7K | 5.6K | Oct 2026 | Apache-2.0 |
| [Ormar](#ormar) | 123.9K | 1.8K | Nov 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[SQLAlchemy](#sqlalchemy) has the most monthly downloads in this comparison, at 413.8M.

## Capabilities

| Library | Awaitable ORM queries | Schema migration tools |
| --- | --- | --- |
| [SQLAlchemy](#sqlalchemy) | Yes | Via plugin |
| [Django ORM](#django) | Yes | Yes |
| [Peewee](#peewee) | Yes | Yes |
| [SQLModel](#sqlmodel) | Yes | Via plugin |
| [Pony ORM](#pony-orm) | No | Undocumented |
| [Piccolo](#piccolo) | Yes | Yes |
| [Tortoise ORM](#tortoise-orm) | Yes | Yes |
| [Ormar](#ormar) | Yes | Via plugin |

## Libraries

### SQLAlchemy

[GitHub](https://github.com/sqlalchemy/sqlalchemy) · [PyPI](https://pypi.org/project/SQLAlchemy) · [Docs](https://docs.sqlalchemy.org)

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
- Capabilities: [From the SQLAlchemy docs](https://docs.sqlalchemy.org)

**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.

**Watch out for**

- **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.

```sh
pip install SQLAlchemy
```

**fastapi/sqlmodel** (18.6K stars)

[fastapi/sqlmodel](https://github.com/fastapi/sqlmodel) 

```python
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)
```

[sqlmodel/main.py](https://github.com/fastapi/sqlmodel/blob/f56eb44235e9102c0a192c96fa14c1f960f52bb2/sqlmodel/main.py) · [More projects using SQLAlchemy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20SQLAlchemy%20for%20filtered%20event%20responses%2C%20schema%20initialization%20and%20retrieval%20of%20entities%20after%20raw%20searches&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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()

```

From [async_orm.py](https://docs.sqlalchemy.org/en/21/orm/quickstart.html)

### Django ORM

[GitHub](https://github.com/django/django) · [PyPI](https://pypi.org/project/Django) · [Docs](https://docs.djangoproject.com/)

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
- Capabilities: [From the Django ORM docs](https://docs.djangoproject.com/)

**Strengths**

- **Migrations included.** makemigrations writes migrations from model changes, and migrate applies them.

**Watch out for**

- **Transactions run synchronously.** Async code wraps transactional ORM work in a synchronous function called through sync_to_async.

```sh
pip install Django
```

**django-oscar/django-oscar** (6.6K stars)

[django-oscar/django-oscar](https://github.com/django-oscar/django-oscar) 

```python
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,
            )
```

[src/oscar/apps/order/utils.py](https://github.com/django-oscar/django-oscar/blob/a5ed3c9c17d4cf6ee18aa9795b493172416ab68b/src/oscar/apps/order/utils.py#L258-L270) · [More projects using Django ORM →](https://dashboard.exa.ai/playground/search?q=Django%20GitHub%20projects)

**Quickstart**

```python
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')

```

From [settings/](https://docs.djangoproject.com/en/6.1/topics/settings/)

### Peewee

[GitHub](https://github.com/coleifer/peewee) · [PyPI](https://pypi.org/project/peewee) · [Docs](https://docs.peewee-orm.com/)

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
- Capabilities: [From the Peewee docs](https://docs.peewee-orm.com/)

**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.

**Watch out for**

- **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.

```sh
pip install peewee
```

**blakeblackshear/frigate** (37.5K stars)

[blakeblackshear/frigate](https://github.com/blakeblackshear/frigate) 

```python
@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)

```

[frigate/api/event.py](https://github.com/blakeblackshear/frigate/blob/ec5f6d4f7fcfb3e9ab45ec63026cf0cf0dc1a7db/frigate/api/event.py#L490-L518) · [More projects using Peewee →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20peewee%20for%20filtered%20event%20responses%2C%20schema%20initialization%20and%20retrieval%20of%20entities%20after%20raw%20searches&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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')

```

From [quickstart.html](https://docs.peewee-orm.com/en/latest/peewee/querying.html)

### SQLModel

[GitHub](https://github.com/fastapi/sqlmodel) · [PyPI](https://pypi.org/project/sqlmodel) · [Docs](https://sqlmodel.tiangolo.com)

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
- Capabilities: [From the SQLModel docs](https://sqlmodel.tiangolo.com)

**Strengths**

- **One model, two roles.** A single class works as the Pydantic model and the SQLAlchemy table.

```sh
pip install sqlmodel
```

**fastapi/full-stack-fastapi-template** (46.3K stars)

[fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template) 

```python
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
```

[backend/app/crud.py](https://github.com/fastapi/full-stack-fastapi-template/blob/77e550a73bb49dd2967622c5ed11bf7a49603c93/backend/app/crud.py#L10-L17) · [More projects using SQLModel →](https://dashboard.exa.ai/playground/search?q=sqlmodel%20GitHub%20projects)

**Quickstart**

```python
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()

```

From [create-db-and-table/](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/)

### Pony ORM

[GitHub](https://github.com/ponyorm/pony) · [PyPI](https://pypi.org/project/pony) · [Docs](https://docs.ponyorm.org)

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
- Capabilities: [From the Pony ORM docs](https://docs.ponyorm.org)

**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.

**Watch out for**

- **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.

```sh
pip install pony
```

**Tribler/tribler** (5.4K stars)

[Tribler/tribler](https://github.com/Tribler/tribler) 

```python
@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))

```

[src/tribler/core/database/store.py](https://github.com/Tribler/tribler/blob/af0f93e734e5d612dae05a3dc1cca0aa0d3cd8d8/src/tribler/core/database/store.py#L845-L857) · [More projects using Pony ORM →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pony%20for%20filtered%20event%20responses%2C%20schema%20initialization%20and%20retrieval%20of%20entities%20after%20raw%20searches&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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')

```

From [firststeps.html](https://docs.ponyorm.org/firststeps.html)

### Piccolo

[GitHub](https://github.com/piccolo-orm/piccolo) · [PyPI](https://pypi.org/project/piccolo) · [Docs](https://piccolo-orm.readthedocs.io/en/latest/index.html)

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
- Capabilities: [From the Piccolo docs](https://piccolo-orm.readthedocs.io/en/latest/index.html)

**Strengths**

- **Migrations and admin included.** The package ships a User model, authentication, migrations, and an admin GUI.

```sh
pip install "piccolo[sqlite]"
```

**piccolo-orm/piccolo_admin** (467 stars)

[piccolo-orm/piccolo_admin](https://github.com/piccolo-orm/piccolo_admin) 

```python
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)
```

[piccolo_admin/example/tables.py](https://github.com/piccolo-orm/piccolo_admin/blob/d6053adc9f6d2db49cba9bcce97914ac3b2b989a/piccolo_admin/example/tables.py#L324-L328) · [More projects using Piccolo →](https://dashboard.exa.ai/playground/search?q=piccolo%20GitHub%20projects)

**Quickstart**

```python
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()

```

From [table.py](https://raw.githubusercontent.com/piccolo-orm/piccolo/1.39.0/piccolo/table.py)

### Tortoise ORM

[GitHub](https://github.com/tortoise/tortoise-orm) · [PyPI](https://pypi.org/project/tortoise-orm) · [Docs](https://tortoise.github.io)

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
- Capabilities: [From the Tortoise ORM docs](https://tortoise.github.io)

**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.

**Watch out for**

- **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.

```sh
pip install tortoise-orm
```

**tortoise/aerich** (1.1K stars)

[tortoise/aerich](https://github.com/tortoise/aerich) 

```python
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
```

[aerich/__init__.py](https://github.com/tortoise/aerich/blob/a4b8186d77c380b67d443bf3b84732b810b3d2bb/aerich/__init__.py) · [More projects using Tortoise ORM →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20tortoise-orm%20for%20filtered%20event%20responses%2C%20schema%20initialization%20and%20retrieval%20of%20entities%20after%20raw%20searches&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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())

```

From [basic.py](https://raw.githubusercontent.com/tortoise/tortoise-orm/1.1.9/tortoise/contrib/test/__init__.py)

### Ormar

[GitHub](https://github.com/ormar-orm/ormar) · [PyPI](https://pypi.org/project/ormar) · [Docs](https://ormar-orm.github.io/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
- Capabilities: [From the Ormar docs](https://ormar-orm.github.io/ormar/)

**Strengths**

- **Pydantic models as tables.** Each model validates data with Pydantic and maps a table.

**Watch out for**

- **Migrations through Alembic.** Tables are based on SQLAlchemy, so schema migrations run through Alembic.

```sh
pip install ormar aiosqlite
```

**uriyyo/fastapi-pagination** (1.7K stars)

[uriyyo/fastapi-pagination](https://github.com/uriyyo/fastapi-pagination) 

```python
async def apaginate(
    query: QuerySet[TModel] | type[TModel],
    params: AbstractParams | None = None,
    *,
    transformer: AsyncItemsTransformer | None = None,
    additional_data: AdditionalData | None = None,
    config: Config | None = None,
) -> Any:
    if not isinstance(query, QuerySet):
        query = query.objects

    return await run_async_flow(
        generic_flow(
            async_=True,
            total_flow=flow_expr(lambda: query.count()),
            limit_offset_flow=flow_expr(lambda raw_params: generic_query_apply_params(query, raw_params).all()),
            params=params,
            transformer=transformer,
            additional_data=additional_data,
            config=config,
        )
    )
```

[fastapi_pagination/ext/ormar.py](https://github.com/uriyyo/fastapi-pagination/blob/7bfd38db3d3a8bb79eb9ef7c1f2f13d038a45a91/fastapi_pagination/ext/ormar.py) · [More projects using Ormar →](https://dashboard.exa.ai/playground/search?q=ormar%20GitHub%20projects)

**Quickstart**

```python
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())

```

From [migrations/](https://ormar-orm.github.io/ormar/latest/models/migrations/)

## FAQ

### Which Python ORM should I use?

[SQLAlchemy](#sqlalchemy) covers both raw SQL expressions and mapped models. [Django ORM](#django) comes with a Django project, [SQLModel](#sqlmodel) shares Pydantic models with FastAPI, and [Tortoise ORM](#tortoise-orm) and [Piccolo](#piccolo) are written around `asyncio`. [Peewee](#peewee) is a single module with no required dependencies.

### SQLModel vs SQLAlchemy: which should I use?

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.

### Does SQLAlchemy support async?

Yes. SQLAlchemy runs ORM queries through `AsyncSession` with an async database driver. Each concurrent task needs its own `AsyncSession`.

### SQLAlchemy vs Django ORM: what is the difference?

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 vs SQLAlchemy: which should I use?

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.

### Which Python ORMs include schema migrations?

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.

## How this page was built

Data checked Nov 19, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python database ORM libraries SQLAlchemy Peewee Tortoise Pony code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
