Registry / database / ormar
library0.26.0pypypi✓ verified 85d ago

Ormar is an async ORM for Python, designed with FastAPI and Pydantic validation in mind, supporting Postgres, MySQL, and SQLite. It provides a single model definition that acts as both an ORM model and a Pydantic model. Currently at version 0.23.1, it maintains an active development and release cadence, frequently pushing updates including vulnerability fixes and new features.

pip install ormar
INSTALL
IMPORT
SIG · ORMAR
O
ormar
databasepythonv0.26.0
Install
5.3s avg
Import
1137ms
Disk
52MB
Pass rate
6/ 10
Env Coverage6 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.24.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
3/4 runs
✓ 6.18s
py 3.11
3/4 runs
✓ 5.03s
py 3.12
3/4 runs
✓ 4.23s
py 3.13
3/4 runs
✓ 4.43s
py 3.9
✓ —
✓ 6.75s
52MB installed
● package 52MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Model
from ormar import Model
OrmarConfig
from ormar import OrmarConfig
class Meta: ...
Since v0.20.0, model configuration moved from an inner `Meta` class to an instance of `OrmarConfig` assigned to the `ormar_config` attribute.
DatabaseConnection
from ormar import DatabaseConnection
import databases; database = databases.Database(...)
Since v0.22.0, `ormar` replaced the `databases` library with native async SQLAlchemy via `DatabaseConnection`.
Integer
from ormar import Integer
String
from ormar import String
Boolean
from ormar import Boolean

This quickstart demonstrates how to set up an Ormar model, connect to an in-memory SQLite database, create tables, and perform basic CRUD operations. It uses the modern `OrmarConfig` and `DatabaseConnection` patterns. Note that for persistent databases, `alembic` is recommended for migrations, and `create_all` is typically run only once during setup or testing.

import asyncio import sqlalchemy import ormar # 1. Define Database Connection and Metadata DATABASE_URL = "sqlite+aiosqlite:///test.db" # This assumes a base config for all models. For complex apps, use `base_ormar_config.copy()` base_ormar_config = ormar.OrmarConfig( metadata=sqlalchemy.MetaData(), database=ormar.DatabaseConnection(DATABASE_URL), ) # 2. Define an Ormar Model class User(ormar.Model): ormar_config = base_ormar_config.copy(tablename="users") id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) is_active: bool = ormar.Boolean(default=True) async def main(): # 3. Connect to the database and create tables if not base_ormar_config.database.is_connected: await base_ormar_config.database.connect() # Create tables (only once, usually in a migration or startup script) # For a persistent DB, use alembic. For quickstart, create all. print("Creating tables...") engine = sqlalchemy.create_engine(DATABASE_URL.replace('+aiosqlite', '')) base_ormar_config.metadata.create_all(engine) print("Tables created.") # 4. Create a new user print("Creating user Jane Doe...") jane = await User.objects.create(name="Jane Doe") print(f"Created user: {jane.id} - {jane.name} (active: {jane.is_active})") # 5. Retrieve all users print("Retrieving all users...") users = await User.objects.all() for user in users: print(f"Found user: {user.id} - {user.name} (active: {user.is_active})") # 6. Disconnect from the database print("Disconnecting from database...") if base_ormar_config.database.is_connected: await base_ormar_config.database.disconnect() print("Disconnected.") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
breakingA high severity vulnerability (CVE-2026-27953) in model initialization allowed injection of `__pk_only__` and `__excluded__` parameters through user-supplied `**kwargs`, bypassing Pydantic validation or nullifying fields.
fix
Upgrade to ormar `0.23.1` or newer immediately.
affects: All versions prior to 0.23.1
breakingA critical vulnerability (CVE-2026-26198) in aggregate functions allowed arbitrary SQL execution through user input due to improper SQL query generation.
fix
Upgrade to ormar `0.23.0` or newer immediately.
affects: 0.9.9 - 0.12.2 and 0.20.0b1 - 0.22.0
breakingVersion 0.22.0 migrated from the `databases` library to native async SQLAlchemy. This requires changing database connection imports and potentially connection string formats.
fix
Replace `import databases` with `from ormar import DatabaseConnection`. Database URLs must now use async drivers (e.g., `sqlite+aiosqlite:///` instead of `sqlite:///`).
affects: 0.22.0 and later
breakingStarting with version 0.20.0, model configuration transitioned from an inner `Meta` class to an instance of `ormar.OrmarConfig` assigned to the `ormar_config` attribute.
fix
Refactor `class Meta: ...` within your models to `ormar_config = ormar.OrmarConfig(...)`. It's recommended to create a base `OrmarConfig` and use its `copy()` method for individual models.
affects: 0.20.0 and later
breakingOrmar `0.20.0` introduced support for Pydantic v2. This includes changes to how `choices` are handled (now `ormar.Enum`) and deprecation of `pydantic_only` fields. This might require adjustments in model field definitions.
fix
Migrate Pydantic v1 models to v2 syntax. Replace `choices` parameter in fields with `ormar.Enum`. `pydantic_only` fields are removed.
affects: 0.20.0 and later
breakingSupport for Python 3.8 was dropped in `0.21.0`, and Python 3.9 was dropped in `0.23.0`. Additionally, SQLAlchemy 1.4 support was dropped in `0.21.0` in favor of SQLAlchemy 2.0.
fix
Ensure your project runs on Python 3.10 or newer. Upgrade SQLAlchemy to version 2.0 or compatible version.
affects: 0.21.0 and later (Python 3.8), 0.23.0 and later (Python 3.9), 0.21.0 and later (SQLAlchemy 1.4)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'databases'
This error occurs because the 'databases' library, which 'ormar' historically depended on for database connections or is often used in 'ormar' examples, is not installed in the environment.
fix
Install the 'databases' library using pip: `pip install databases`
sqlite:///db.sqlite (or postgresql://user:pass@host/db) connection error or driver-specific exception
'ormar' is an asynchronous ORM and requires async-compatible database drivers. Using synchronous database URLs (e.g., `sqlite://` or `postgresql://`) instead of their async equivalents will lead to connection failures.
fix
Update the database URL to use an async driver. For example:
- SQLite: `sqlite+aiosqlite:///db.sqlite`
- PostgreSQL: `postgresql+asyncpg://user:pass@host/db`
- MySQL: `mysql+aiomysql://user:pass@host/db`
AttributeError: 'ModelMeta' object has no attribute 'get_column_alias'
This error arises when an 'ormar' model is incorrectly defined by inheriting from `ormar.ModelMeta` instead of the proper base class, `ormar.Model`.
fix
Ensure your 'ormar' models inherit from `ormar.Model`.
```python
import ormar
import sqlalchemy

database = ormar.DatabaseConnection("sqlite+aiosqlite:///test.db")
metadata = sqlalchemy.MetaData()

class MyModel(ormar.Model): # Correct inheritance
    class OrmarConfig:
        tablename = "mymodel"
        metadata = metadata
        database = database
    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)
```
RelationshipInstanceError: Relationship error - ForeignKey OrmarBaseUserModel is of type <class 'uuid.UUID'> while <class 'str'> passed as a parameter.
This specific error occurs when attempting to assign a string value to an 'ormar' ForeignKey field that is defined to expect a `uuid.UUID` object, indicating a type mismatch during relation assignment, often with older 'ormar' versions or incorrect manual type handling.
fix
Ensure you are using 'ormar' version 0.7.3 or higher, which includes a fix for this UUID type handling. If the issue persists, ensure that any UUID values passed to the ForeignKey are actual `uuid.UUID` objects, not strings, or pass the full related model instance.
IntegrityError (e.g., sqlite3.IntegrityError, asyncpg.exceptions.UniqueViolationError, pymysql.IntegrityError)
This error, originating from the database backend, signals a violation of a database constraint, such as attempting to save a record with a duplicate primary key, a non-unique value in a unique field, or an invalid foreign key reference.
fix
For existing records, use `model.update()` instead of `model.save()`, or use `Model.objects.upsert()` for a create-or-update operation. For unique constraint errors, ensure the value is unique. For foreign key errors, verify that the related object exists in the database before assignment.
Upgrade
Version history
0.26.0latest on PyPI · released Jun 8, 2026
Audit
Dependencies
sqlalchemyrequiredUsed for query building and database interaction.
pydanticrequiredUsed for data validation and model serialization/deserialization.
aiosqliteoptionalRequired for async SQLite connections.
asyncpgoptionalRequired for async PostgreSQL connections.
pymysqloptionalRequired for async MySQL connections.
Agent activity
18 hits · last 30 days
node
14
Amazon
1
Resources