A Beginner's Guide to Tortoise ORM and PostgreSQL

155 views 13 slides Dec 26, 2024
Slide 1
Slide 1 of 13
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13

About This Presentation

Unlock the power of Python with Tortoise ORM and PostgreSQL in this comprehensive beginner's guide! Whether you're new to Object-Relational Mappers (ORMs) or want to integrate PostgreSQL with your Python projects, this video is your go-to resource.

In this step-by-step tutorial, you'll ...


Slide Content

Samuel Folasayo
Master Tortoise ORM &
PostgreSQL: Your Ultimate
Beginner's Guide
Simplifying Python/PostgreSQL Database Integration
Joe Nyirenda

Learning Objectives
ā—Understand the basics of Tortoise ORM and PostgreSQL
ā—Learn how to setup and configure your environment
ā—Define models and perform CRUD operations
ā—Query data and handle relationships effectively
ā—Build efficient and scalable Python applications with Tortoise ORM and
PostgreSQL

What is Tortoise ORM?
A lightweight Object Relational Mapper (ORM) for Python.
Built with asyncio support for high-performance applications.
Simple syntax and seamless integration with Python's async features.

Key Features:
Asynchronous execution
Schema generation
Support for multiple backends, including PostgreSQL.

Why PostgreSQL?
Open-source, powerful, and reliable relational database system.
Features advanced data types and robust query capabilities.
Ideal for scalable and complex applications.

Why Use Tortoise ORM with PostgreSQL?
Simplifies database interactions.
Enhances developer productivity.
Combines PostgreSQL's power with Python's simplicity.

Setting Up the Environment
Prerequisites:
Python 3.7+
PostgreSQL installed on your system.

Install Required Packages:
pip install tortoise-orm asyncpg

Create a Database:
CREATE DATABASE tortoise_demo;

Connecting to PostgreSQL
import os
from dotenv import load_dotenv
from tortoise import Tortoise

# Load environment variables from a .env file (if you're using one)
load_dotenv()

# Fetch username and password from environment variables
DB_USERNAME = os.getenv('DB_USERNAME')
DB_PASSWORD = os.getenv('DB_PASSWORD')

# Define the database connection using environment variables
DATABASE_CONFIG = {
"connections": {
"default": f"postgres://{DB_USERNAME}:{DB_PASSWORD}@localhost:5432/tortoise_demo"
},
"apps": {
"models": {
"models": ["__main__"],
"default_connection": "default",
},
},
}

async def init():
await Tortoise.init(config=DATABASE_CONFIG)
await Tortoise.generate_schemas()

Defining Models
Example Model:
The code below defines a Tortoise ORM model for a User with fields for id, name, email,
and created_at, representing a user entity in a database.
from tortoise.models import Model
from tortoise import fields

class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=50)
email = fields.CharField(max_length=100, unique=True)
created_at = fields.DatetimeField( auto_now_add=True)

def __str__(self):
return self.name

Basic CRUD Operations
Create:
user = await User.create(name="John Doe", email="[email protected]")

user = await User.get(id=1)
print(user.name)

Read:
Update:
user.name = "Jane Doe"
await user.save()

Delete:
await user.delete()

Querying Data
Example Queries:
Filter by Condition:

users = await User.filter(name__icontains="John")

users = await User.all().order_by( "-created_at")
Order by Field:

Paginate:

users = await User.all().offset( 10).limit(10)

Relationships
Defining Relationships:
class Post(Model):
id = fields.IntField(pk=True)
title =
fields.CharField(max_length=100)
content = fields.TextField()
author =
fields.ForeignKeyField( "models.User",
related_name="posts")

Fetching Related Data:
user = await
User.get(id=1).prefetch_related( "po
sts")
for post in user.posts:
print(post.title)

Explanation:

In this example, we are modeling a one-to-many relationship between the User
and Post models using Foreign Key in Tortoise ORM.
One-to-many relationship: This means that a single user can have many posts,
but each post is associated with exactly one user.

Putting It All Together
Example: Complete Workflow
async def main():
await init()

# Create user and post
user = await User.create(name="Alice", email="[email protected]" )
post = await Post.create(title="My First Post", content="Hello World!",
author=user)

# Query and display
users = await User.all().prefetch_related( "posts")
for user in users:
print(f"{user.name} wrote {len(user.posts)} posts.")

await main()

Results

Conclusion
Tortoise ORM simplifies database interactions in Python
PostgreSQL provides a robust backend for scalable applications
Combined, they enable fast and efficient development