Skip to main content

Easy async ORM for python, built with relations in mind

Project description

https://travis-ci.com/Zeliboba5/tortoise-orm.svg?branch=master https://coveralls.io/repos/github/Zeliboba5/tortoise-orm/badge.svg?branch=master

Introduction

Tortoise is easy-to-use asyncio ORM inspired by Django.

It is built with relations between models in mind and provides simple api for it, that gives you potential for building web services with easy abstractions.

You can find docs at readthedocs

Disclaimer

Tortoise is young project and breaking changes without following semantic versioning are to be expected

Installation

First you have to install tortoise like this:

pip install tortoise-orm

Then you should install your db driver

pip install asyncpg aiosqlite

Tutorial

Primary entity of tortoise is tortoise.models.Model. You can start writing models like this:

from tortoise.models import Model
from tortoise import fields

class Tournament(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()

    def __str__(self):
        return self.name


class Event(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    tournament = fields.ForeignKeyField('models.Tournament', related_name='events')
    participants = fields.ManyToManyField('models.Team', related_name='events', through='event_team')

    def __str__(self):
        return self.name


class Team(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()

    def __str__(self):
        return self.name

Then in init part of your app you should init models like this (make sure that you import your models before calling init, tortoise must see them to init normally):

from tortoise.backends.asyncpg.client import AsyncpgDBClient
from tortoise import Tortoise
from app import models # without importing models Tortoise can't find and init them


async def init():
    db = AsyncpgDBClient(
        host='localhost',
        port=5432,
        user='postgres',
        password='qwerty123',
        database='events'
    )

    await db.create_connection()
    Tortoise.init(db)
    # You can generate schema for your models like this, but don't do this if you have schema already:
    await generate_schema(db)

After that you can start using your models:

# Create instance by save
tournament = Tournament(name='New Tournament')
await tournament.save()

# Or by .create()
await Event.create(name='Without participants', tournament=tournament)
event = await Event.create(name='Test', tournament=tournament)
participants = []
for i in range(2):
    team = Team.create(name='Team {}'.format(i + 1))
    participants.append(team)

# M2M Relationship management is quite straightforward
# (also look for methods .remove(...) and .clear())
await event.participants.add(*participants)

# You can query related entity just with async for
async for team in event.participants:
    pass

# After making related query you can iterate with regular for,
# which can be extremely convenient for using with other packages,
# for example some kind of serializers with nested support
for team in event.participants:
    pass


# Or you can make preemptive call to fetch related objects
selected_events = await Event.filter(
    participants=participants[0].id
).prefetch_related('participants', 'tournament')

# Tortoise supports variable depth of prefetching related entities
# This will fetch all events for team and in those events tournaments will be prefetched
await Team.all().prefetch_related('events__tournament')

# You can filter and order by related models too
await Tournament.filter(
    events__name__in=['Test', 'Prod']
).order_by('-events__participants__name').distinct()

If you want to contribute check out issues, or just straightforwardly create PR

Project details


Release history Release notifications

This version
History Node

0.9.4

History Node

0.9.2

History Node

0.9.1

History Node

0.9.0

History Node

0.8.2

History Node

0.8.1

History Node

0.8.0

History Node

0.7.10

History Node

0.7.9

History Node

0.7.8

History Node

0.7.7

History Node

0.7.6

History Node

0.7.5

History Node

0.7.4

History Node

0.7.3

History Node

0.7.2

History Node

0.7.1

History Node

0.7.0

History Node

0.6.2

History Node

0.6.1

History Node

0.6.0

History Node

0.5.5

History Node

0.5.4

History Node

0.5.3

History Node

0.5.2

History Node

0.5.1

History Node

0.5.0

History Node

0.4.0

History Node

0.3.3

History Node

0.3.2

History Node

0.3.1

History Node

0.3.0

History Node

0.2.0

History Node

0.1.3

History Node

0.1.2

History Node

0.1.1

History Node

0.1.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
tortoise-orm-0.9.4.tar.gz (133.9 kB) Copy SHA256 hash SHA256 Source None Jul 17, 2018

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging CloudAMQP CloudAMQP RabbitMQ AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page