tortoise-orm 0.24.2
pip install tortoise-orm
Released:
Easy async ORM for python, built with relations in mind
Navigation
Verified details
These details have been verified by PyPIMaintainers
Unverified details
These details have not been verified by PyPIProject links
Meta
- License: Apache Software License (Apache-2.0)
- Author: Andrey Bondar
- Tags sql, mysql, postgres, psql, sqlite, aiosqlite, asyncpg, relational, database, rdbms, orm, object mapper, async, asyncio, aio, psycopg
- Requires: Python >=3.9
-
Provides-Extra:
accel
,aiomysql
,asyncmy
,asyncodbc
,asyncpg
,psycopg
Classifiers
- Development Status
- Framework
- Intended Audience
- License
- Operating System
- Programming Language
- Topic
Project description
Introduction
Tortoise ORM is an easy-to-use asyncio ORM (Object Relational Mapper) inspired by Django.
You can find the docs at Documentation
Tortoise ORM supports CPython 3.9 and later for SQLite, MySQL, PostgreSQL, Microsoft SQL Server, and Oracle.
Why was Tortoise ORM built?
Python has many existing and mature ORMs, unfortunately they are designed with an opposing paradigm of how I/O gets processed. asyncio is relatively new technology that has a very different concurrency model, and the largest change is regarding how I/O is handled.
However, Tortoise ORM is not the first attempt of building an asyncio ORM. While there are many cases of developers attempting to map synchronous Python ORMs to the async world, initial attempts did not have a clean API.
Hence we started Tortoise ORM.
Tortoise ORM is designed to be functional, yet familiar, to ease the migration of developers wishing to switch to asyncio.
It also performs well when compared to other Python ORMs. In our benchmarks, where we measure different read and write operations (rows/sec, more is better), it’s trading places with Pony ORM:
How is an ORM useful?
An Object-Relational Mapper (ORM) abstracts database interactions, allowing developers to work with databases using high-level, object-oriented code instead of raw SQL.
Reduces boilerplate SQL, allowing faster development with cleaner, more readable code.
Helps prevent SQL injection by using parameterized queries.
Centralized schema and relationship definitions make code easier to manage and modify.
Handles schema changes through version-controlled migrations.
Getting Started
Installation
The following table shows the available installation options for different databases (note that there are multiple options of clients for some databases):
Database |
Installation Command |
---|---|
SQLite |
pip install tortoise-orm |
PostgreSQL (psycopg) |
pip install tortoise-orm[psycopg] |
PostgreSQL (asyncpg) |
pip install tortoise-orm[asyncpg] |
MySQL (aiomysql) |
pip install tortoise-orm[aiomysql] |
MySQL (asyncmy) |
pip install tortoise-orm[asyncmy] |
MS SQL |
pip install tortoise-orm[asyncodbc] |
Oracle |
pip install tortoise-orm[asyncodbc] |
Quick Tutorial
Define the models by inheriting from tortoise.models.Model.
from tortoise.models import Model
from tortoise import fields
class Tournament(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
class Event(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
tournament = fields.ForeignKeyField('models.Tournament', related_name='events')
participants = fields.ManyToManyField('models.Team', related_name='events', through='event_team')
class Team(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
After defining the models, Tortoise ORM needs to be initialized to establish the relationships between models and connect to the database. The code below creates a connection to a SQLite DB database with the aiosqlite client. generate_schema sets up schema on an empty database. generate_schema is for development purposes only, check out aerich or other migration tools for production use.
from tortoise import Tortoise, run_async
async def init():
# Here we connect to a SQLite DB file.
# also specify the app name of "models"
# which contain models from "app.models"
await Tortoise.init(
db_url='sqlite://db.sqlite3',
modules={'models': ['app.models']}
)
# Generate the schema
await Tortoise.generate_schemas()
run_async(main())
run_async is a helper function to run simple Tortoise scripts. Check out Documentation for FastAPI, Sanic and other integrations.
With the Tortoise initialized, the models are available for use:
async def main():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
modules={'models': ['app.models']}
)
await Tortoise.generate_schemas()
# Creating an instance with .save()
tournament = Tournament(name='New Tournament')
await tournament.save()
# Or with .create()
await Event.create(name='Without participants', tournament=tournament)
event = await Event.create(name='Test', tournament=tournament)
participants = []
for i in range(2):
team = await Team.create(name='Team {}'.format(i + 1))
participants.append(team)
# Many to Many Relationship management is quite straightforward
# (there are .remove(...) and .clear() too)
await event.participants.add(*participants)
# Iterate over related entities with the async context manager
async for team in event.participants:
print(team.name)
# The related entities are cached and can be iterated in the synchronous way afterwards
for team in event.participants:
pass
# Use prefetch_related to fetch related objects
selected_events = await Event.filter(
participants=participants[0].id
).prefetch_related('participants', 'tournament')
for event in selected_events:
print(event.tournament.name)
print([t.name for t in event.participants])
# Prefetch multiple levels of related entities
await Team.all().prefetch_related('events__tournament')
# Filter and order by related models too
await Tournament.filter(
events__name__in=['Test', 'Prod']
).order_by('-events__participants__name').distinct()
run_async(main())
Learn more at the documentation site
Migration
Tortoise ORM uses Aerich as its database migration tool, see more detail at its docs.
Contributing
Please have a look at the Contribution Guide.
ThanksTo
Powerful Python IDE Pycharm from Jetbrains.
License
This project is licensed under the Apache License - see the LICENSE.txt file for details.
Project details
Verified details
These details have been verified by PyPIMaintainers
Unverified details
These details have not been verified by PyPIProject links
Meta
- License: Apache Software License (Apache-2.0)
- Author: Andrey Bondar
- Tags sql, mysql, postgres, psql, sqlite, aiosqlite, asyncpg, relational, database, rdbms, orm, object mapper, async, asyncio, aio, psycopg
- Requires: Python >=3.9
-
Provides-Extra:
accel
,aiomysql
,asyncmy
,asyncodbc
,asyncpg
,psycopg
Classifiers
- Development Status
- Framework
- Intended Audience
- License
- Operating System
- Programming Language
- Topic
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file tortoise_orm-0.24.2.tar.gz
.
File metadata
- Download URL: tortoise_orm-0.24.2.tar.gz
- Upload date:
- Size: 126.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 83d2373efafc1c5d668c3c5bd4e1e7f4a219526e850909ffe88f184da3808fdb |
|
MD5 | fa3177acfcd186ccdef0936dabc79f90 |
|
BLAKE2b-256 | 49e8ac7cc41c297f20b3642351e5ff16f53beddea37be285f33f30308838d704 |
File details
Details for the file tortoise_orm-0.24.2-py3-none-any.whl
.
File metadata
- Download URL: tortoise_orm-0.24.2-py3-none-any.whl
- Upload date:
- Size: 165.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d2381b26f48bd2f5c5d978ddf9bb40b2b81b2dbb78dab6a17882a156de8b5c62 |
|
MD5 | bf9f1c692f0da044c28d0bb13a1bc6b8 |
|
BLAKE2b-256 | 48666091aaad68c6e390e85a90cc2d9f9d12f43a577829c8b8dbfe51191a71db |