Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Familiar asyncio ORM for python, built with relations in mind

License

NotificationsYou must be signed in to change notification settings

tortoise/tortoise-orm

Repository files navigation

https://img.shields.io/pypi/v/tortoise-orm.svg?style=flathttps://pepy.tech/badge/tortoise-orm/monthhttps://github.com/tortoise/tortoise-orm/actions/workflows/ci.yml/badge.svg?branch=develophttps://app.codacy.com/project/badge/Grade/844030d0cb8240d6af92c71bfac764ff

Introduction

Tortoise ORM is an easy-to-useasyncio ORM(Object Relational Mapper) inspired by Django.

You can find the docs atDocumentation

Note

Tortoise ORM is a young project and breaking changes are to be expected.We keep aChangelog and it will have possible breakage clearly documented.

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 anasyncio 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 toasyncio.

It also performs well when compared to other Python ORMs. Inour benchmarks, where we measure different read and write operations (rows/sec, more is better), it's trading places with Pony ORM:

https://raw.githubusercontent.com/tortoise/tortoise-orm/develop/docs/ORM_Perf.png

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):

Available Installation Options
DatabaseInstallation Command
SQLitepip 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 SQLpip install tortoise-orm[asyncodbc]
Oraclepip install tortoise-orm[asyncodbc]

Quick Tutorial

Define the models by inheriting fromtortoise.models.Model.

fromtortoise.modelsimportModelfromtortoiseimportfieldsclassTournament(Model):id=fields.IntField(primary_key=True)name=fields.TextField()classEvent(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')classTeam(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 theaiosqlite client.generate_schema sets up schema on an empty database.generate_schema is for development purposes only, check outaerich or other migration tools for production use.

fromtortoiseimportTortoise,run_asyncasyncdefinit():# Here we connect to a SQLite DB file.# also specify the app name of "models"# which contain models from "app.models"awaitTortoise.init(db_url='sqlite://db.sqlite3',modules={'models': ['app.models']}    )# Generate the schemaawaitTortoise.generate_schemas()run_async(main())

run_async is a helper function to run simple Tortoise scripts. Check outDocumentation for FastAPI, Sanic and other integrations.

With the Tortoise initialized, the models are available for use:

asyncdefmain():awaitTortoise.init(db_url='sqlite://db.sqlite3',modules={'models': ['app.models']}    )awaitTortoise.generate_schemas()# Creating an instance with .save()tournament=Tournament(name='New Tournament')awaittournament.save()# Or with .create()awaitEvent.create(name='Without participants',tournament=tournament)event=awaitEvent.create(name='Test',tournament=tournament)participants= []foriinrange(2):team=awaitTeam.create(name='Team {}'.format(i+1))participants.append(team)# Many to Many Relationship management is quite straightforward# (there are .remove(...) and .clear() too)awaitevent.participants.add(*participants)# Iterate over related entities with the async context managerasyncforteaminevent.participants:print(team.name)# The related entities are cached and can be iterated in the synchronous way afterwardsforteaminevent.participants:pass# Use prefetch_related to fetch related objectsselected_events=awaitEvent.filter(participants=participants[0].id    ).prefetch_related('participants','tournament')foreventinselected_events:print(event.tournament.name)print([t.namefortinevent.participants])# Prefetch multiple levels of related entitiesawaitTeam.all().prefetch_related('events__tournament')# Filter and order by related models tooawaitTournament.filter(events__name__in=['Test','Prod']    ).order_by('-events__participants__name').distinct()run_async(main())

Learn more at thedocumentation site

Migration

Tortoise ORM usesAerich as its database migration tool, see more detail at itsdocs.

Contributing

Please have a look at theContribution Guide.

ThanksTo

Powerful Python IDEPycharmfromJetbrains.

License

This project is licensed under the Apache License - see theLICENSE.txt file for details.


[8]ページ先頭

©2009-2025 Movatter.jp