Easy async ORM for Python, built with relations in mind
npx @tessl/cli install tessl/pypi-tortoise-orm@0.25.00
# Tortoise ORM
1
2
Easy async ORM for Python, built with relations in mind. Tortoise ORM is an easy-to-use asyncio Object Relational Mapper (ORM) inspired by Django. It provides an intuitive async/await interface for database operations, supporting multiple databases including SQLite, MySQL, PostgreSQL, Microsoft SQL Server, and Oracle.
3
4
## Package Information
5
6
- **Package Name**: tortoise-orm
7
- **Language**: Python
8
- **Installation**: `pip install tortoise-orm`
9
10
## Core Imports
11
12
```python
13
from tortoise import Tortoise, Model
14
from tortoise.fields import IntField, CharField, ForeignKeyField
15
```
16
17
For connections:
18
19
```python
20
from tortoise import connections
21
```
22
23
For query building:
24
25
```python
26
from tortoise.queryset import Q
27
```
28
29
## Basic Usage
30
31
```python
32
from tortoise import Tortoise, fields
33
from tortoise.models import Model
34
35
# Define a model
36
class User(Model):
37
id = fields.IntField(pk=True)
38
name = fields.CharField(max_length=50)
39
email = fields.CharField(max_length=100, unique=True)
40
41
class Meta:
42
table = "users"
43
44
# Initialize Tortoise ORM
45
async def init():
46
await Tortoise.init(
47
db_url='sqlite://db.sqlite3',
48
modules={'models': ['__main__']}
49
)
50
# Generate the schema
51
await Tortoise.generate_schemas()
52
53
# Use the model
54
async def create_user():
55
user = await User.create(name="Alice", email="alice@example.com")
56
print(f"Created user: {user.name}")
57
58
# Query users
59
users = await User.all()
60
user = await User.get(email="alice@example.com")
61
62
# Update
63
user.name = "Alice Smith"
64
await user.save()
65
66
# Delete
67
await user.delete()
68
69
# Clean up
70
async def close():
71
await Tortoise.close_connections()
72
```
73
74
## Architecture
75
76
Tortoise ORM's design centers around these key components:
77
78
- **Models**: Define database tables as Python classes with field definitions and relationships
79
- **Fields**: Typed field classes for data validation and database mapping
80
- **QuerySets**: Lazy query builders that support filtering, ordering, and aggregation
81
- **Connections**: Database connection management with support for multiple databases
82
- **Transactions**: Context managers for database transaction handling
83
- **Signals**: Event system for model lifecycle hooks
84
85
This architecture provides Django-like familiarity with async/await support, making it ideal for modern Python web frameworks like FastAPI, Sanic, and Quart.
86
87
## Capabilities
88
89
### Model Definition and Fields
90
91
Model base class and comprehensive field types for defining database schemas, including data fields (IntField, CharField, JSONField, etc.), relational fields (ForeignKeyField, ManyToManyField, OneToOneField), and field options.
92
93
```python { .api }
94
class Model:
95
def __init__(self, **kwargs): ...
96
async def save(self): ...
97
async def delete(self): ...
98
@classmethod
99
async def create(cls, **kwargs): ...
100
@classmethod
101
async def get(cls, **kwargs): ...
102
@classmethod
103
async def all(cls): ...
104
```
105
106
[Model Definition and Fields](./models.md)
107
108
### Database Operations and Configuration
109
110
Core database management through the Tortoise class, connection handling, schema generation, and database initialization with support for multiple database backends.
111
112
```python { .api }
113
class Tortoise:
114
@classmethod
115
async def init(cls, config=None, db_url=None, modules=None, **kwargs): ...
116
@classmethod
117
async def generate_schemas(cls, safe=True): ...
118
@classmethod
119
async def close_connections(cls): ...
120
@classmethod
121
def describe_models(cls, models=None, serializable=True): ...
122
```
123
124
[Database Operations and Configuration](./database.md)
125
126
### Querying and Filtering
127
128
Advanced query building with QuerySet, Q expressions, filtering, ordering, aggregation, and bulk operations for efficient database access.
129
130
```python { .api }
131
class QuerySet:
132
def filter(self, **kwargs): ...
133
def exclude(self, **kwargs): ...
134
def order_by(self, *fields): ...
135
def limit(self, limit): ...
136
def offset(self, offset): ...
137
async def all(self): ...
138
async def first(self): ...
139
async def count(self): ...
140
```
141
142
[Querying and Filtering](./querying.md)
143
144
### Database Functions and Expressions
145
146
Database function support including text functions (Trim, Length, Lower, Upper), aggregate functions (Count, Sum, Max, Min, Avg), and custom expressions for advanced queries.
147
148
```python { .api }
149
class Function:
150
def __init__(self, *args, **kwargs): ...
151
152
def Trim(field): ...
153
def Length(field): ...
154
def Count(field="*"): ...
155
def Sum(field): ...
156
```
157
158
[Database Functions and Expressions](./functions.md)
159
160
### Framework Integration
161
162
Integration utilities for web frameworks including FastAPI, Pydantic model generation, testing utilities, and database-specific extensions for PostgreSQL and MySQL.
163
164
```python { .api }
165
# FastAPI integration
166
def register_tortoise(app, config=None, **kwargs): ...
167
168
# Pydantic integration
169
def pydantic_model_creator(cls, **kwargs): ...
170
```
171
172
[Framework Integration](./integration.md)
173
174
### Error Handling
175
176
Comprehensive exception hierarchy for handling configuration errors, database operational errors, integrity constraints, validation failures, and query-related exceptions.
177
178
```python { .api }
179
class BaseORMException(Exception): ...
180
class ConfigurationError(BaseORMException): ...
181
class OperationalError(BaseORMException): ...
182
class IntegrityError(OperationalError): ...
183
class ValidationError(BaseORMException): ...
184
```
185
186
[Error Handling](./exceptions.md)
187
188
### Signals and Event Handling
189
190
Model lifecycle event system with decorators for pre/post save and delete signals, enabling custom logic during model operations.
191
192
```python { .api }
193
from tortoise.signals import pre_save, post_save, pre_delete, post_delete
194
195
@pre_save(User)
196
async def on_user_pre_save(sender, instance, **kwargs): ...
197
198
@post_save(User)
199
async def on_user_post_save(sender, instance, created, **kwargs): ...
200
```
201
202
[Signals and Event Handling](./signals.md)
203
204
### Transaction Management
205
206
Context managers and decorators for database transaction handling, ensuring data consistency across multiple operations.
207
208
```python { .api }
209
from tortoise.transactions import in_transaction, atomic
210
211
# Context manager
212
async with in_transaction():
213
await User.create(name="Alice")
214
await User.create(name="Bob")
215
216
# Decorator
217
@atomic()
218
async def create_users():
219
await User.create(name="Alice")
220
await User.create(name="Bob")
221
```
222
223
[Transaction Management](./transactions.md)
224
225
### Validation Framework
226
227
Field validation system with built-in validators for common use cases and support for custom validators.
228
229
```python { .api }
230
from tortoise.validators import (
231
Validator, RegexValidator, MaxLengthValidator,
232
MinLengthValidator, MinValueValidator, MaxValueValidator
233
)
234
235
class EmailValidator(Validator):
236
def __call__(self, value): ...
237
```
238
239
[Validation Framework](./validators.md)
240
241
[Error Handling](./exceptions.md)
242
243
## Global Objects
244
245
### connections
246
247
Global connection handler for managing database connections.
248
249
```python { .api }
250
from tortoise import connections
251
252
# Get a connection
253
connection = connections.get("default")
254
255
# Get all connections
256
all_connections = connections.all()
257
258
# Close all connections
259
await connections.close_all()
260
```
261
262
### Utility Functions
263
264
```python { .api }
265
from tortoise import run_async
266
267
def run_async(coro):
268
"""Simple async runner that cleans up DB connections on exit."""
269
```