Python tortoise-orm Module: Advanced Tutorials and Installation Guide

Python tortoise-orm Module

The tortoise-orm module is a powerful Object-Relational Mapping (ORM) library for Python, designed to work seamlessly with asynchronous frameworks such as asyncio. It offers developers a high-level interface for interacting with databases, making it easier to manage database schemas and queries. Tortoise-ORM supports several databases such as SQLite, PostgreSQL, and MySQL. Furthermore, it’s compatible with Python 3.6 and later versions, enhancing its usability across various applications.

Application Scenarios

Tortoise-ORM is primarily used in web applications and services that require interaction with a relational database. It is particularly beneficial for projects that demand high concurrency, as it leverages Python’s async capabilities. Here are some common application scenarios:

  • Web Development: Many web applications benefit from asynchronous database access, allowing for multiple requests to be processed concurrently without blocking operations.
  • Microservices: Tortoise-ORM can be used in microservices architectures where each service needs its database interactions.
  • Data Analysis: While not its primary use, Tortoise-ORM can facilitate rapid prototyping for data analysis applications that require complex database queries.

Installation Instructions

Tortoise-ORM is not included with the default Python library, so you need to install it separately using pip. To install tortoise-orm, run the following command in your terminal:

1
pip install tortoise-orm

This command will install the latest version of Tortoise-ORM along with its dependencies.

Usage Examples

Example 1: Basic Model Definition and Database Connection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from tortoise import Tortoise, fields
from tortoise.models import Model

# Define the User model with fields
class User(Model):
id = fields.IntField(pk=True) # Primary key
username = fields.CharField(max_length=50) # User's username
email = fields.CharField(max_length=100) # User's email

# Initialize Tortoise-ORM connection with SQLite database
async def init():
await Tortoise.init(db_url='sqlite://db.sqlite3', modules={'models': ['__main__']})
await Tortoise.generate_schemas() # Create tables based on defined models

# Call the init function
import asyncio
asyncio.run(init()) # Run the asynchronous init function

Example 2: Creating and Fetching Users

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async def create_user(username, email):
user = await User.create(username=username, email=email) # Create a new user
return user

async def fetch_users():
users = await User.all() # Fetch all users from the database
return users

# Call the create_user and fetch_users functions
async def main():
await create_user('john_doe', 'john@example.com') # Create a user
users = await fetch_users() # Retrieve users
print(users) # Print the list of users

asyncio.run(main()) # Run the main asynchronous function

Example 3: Updating and Deleting Users

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async def update_user(user_id, new_username):
user = await User.get(id=user_id) # Fetch the user by ID
user.username = new_username # Update the username
await user.save() # Save changes to the database

async def delete_user(user_id):
user = await User.get(id=user_id) # Fetch the user by ID
await user.delete() # Delete the user from the database

# Call the update_user and delete_user functions
async def main():
await update_user(1, 'john_smith') # Update the username of user with ID 1
await delete_user(1) # Delete user with ID 1

asyncio.run(main()) # Run the main asynchronous function

The above examples illustrate how to define models, create, fetch, update, and delete instances using Tortoise-ORM, making it a robust solution for interacting with relational databases asynchronously.


I strongly encourage you to follow my blog, the EVZS Blog, which includes comprehensive guides on using all Python standard libraries for easy reference and learning. By regularly visiting, you will have access to a repository of tutorials that can greatly enhance your programming skills and empower you to tackle various problems effectively. Let’s explore and learn together, ensuring you have all the necessary resources at your fingertips for your Python development journey!