Home Backend Development Python Tutorial ORM framework Tortoise ORM in Python in practice

ORM framework Tortoise ORM in Python in practice

Jun 10, 2023 pm 06:05 PM
python orm tortoise

Tortoise ORM is an asynchronous ORM framework developed based on the Python language and can be used to manage relational databases in Python asynchronous applications.

This article will introduce how to use the Tortoise ORM framework to create, read, update and delete data. You will also learn how to perform simple and complex queries from a relational database.

Preparation

Before starting this tutorial, you need to install Python (Python3.6 is recommended) and install the Tortoise ORM framework.

You can install the Tortoise ORM framework via pip using the following command:

pip install tortoise-orm
Copy after login

Next, we will set up the database and model structure.

Create database connection

Using Tortoise ORM to perform database operations requires connecting to the database first. In this tutorial, we will use a SQLite database.

Tortoise ORM uses environment variables or .config files to manage database connection information. Create a file named .env and the following configuration to achieve database connection.

DATABASE_URL=sqlite://db.sqlite3
Copy after login

Where db.sqlite3 is the file name of the new database you want to create.

At the same time, we also need to use a function in the code to initialize Tortoise ORM:

import os
from dotenv import load_dotenv
from tortoise import Tortoise

# 加载环境变量
load_dotenv()

async def init_db():
    await Tortoise.init(config={
        'connections': {
            'default': os.getenv('DATABASE_URL')
        },
        'apps': {
            'models': {
                'models': ['app.models',],
                'default_connection': 'default'
            }
        }
    })
    await Tortoise.generate_schemas()
Copy after login

In the above code, we use environment variables to obtain the database connection information and pass it to Tortoise ORM for initialization. Then call the Tortoise.generate_schemas() method to generate the corresponding data table for the defined model.

After completing the above operations, we can start creating the model.

Create Model

In this tutorial, we will create a simple blog model that contains title, content, creation time, update time, and author.

from tortoise import fields
from tortoise.models import Model

class Blog(Model):
    id = fields.IntField(pk=True)
    title = fields.CharField(max_length=100)
    content = fields.TextField()
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)
    author = fields.CharField(max_length=100)
Copy after login

In the Blog model of the above code, we use the Model base class and create some fields id, title, content, created_at, updated_at, and author. pk=True specifies that the id field is the primary key. auto_now_add=True and auto_now=True specify that the created_at and updated_at fields should be automatically updated when created and updated respectively.

Now that we have successfully defined a model, let's learn how to use Tortoise ORM for CRUD operations.

Reading and creating data

Reading and creating data using Tortoise ORM is very simple, here is some sample code:

from app.models import Blog

# 创建一个新博客
blog = await Blog.create(title='Tortoise ORM', content='使用Tortoise ORM操作数据库非常方便', author='Alice')

# 读取所有博客
blogs = await Blog.all()
for blog in blogs:
    print(blog.title)

# 根据标题读取指定博客
blog = await Blog.get(title='Tortoise ORM')
print(blog.content)
Copy after login

In the above code, we used The Blog.create() method creates a new blog, uses the Blog.all() method to read all blogs, and uses the Blog.get() The method reads the specified blog based on the title.

Update and delete data

Tortoise ORM also provides methods to update and delete data. Here is some sample code:

# 更新博客的内容
blog.content = 'Tortoise ORM提供了丰富的API来管理数据库'
await blog.save()

# 删除指定的博客
await Blog.filter(title='Tortoise ORM').delete()
Copy after login

In the above code, we have updated the content of the blog using the save() method and filter() and delete()The method deletes the specified blog based on the title.

Execute complex queries

In addition to basic CRUD operations, Tortoise ORM also allows the execution of complex queries. Here are some examples:

# 使用where子句查询特定日期创建的博客
blogs = await Blog.filter(created_at__date='2021-07-12').all()

# 使用order_by子句将博客按更新日期升序排列
blogs = await Blog.all().order_by('updated_at')

# 连接多个过滤器查询具有特定条件的博客
blogs = await Blog.all().filter(title__contains='ORM', author__icontains='Alice')
Copy after login

In the above code, we used filter(), all() and order_by() Method combined with some query parameters, eg. created_at__date, title__contains, and author__icontains, etc., to perform complex queries.

Conclusion

In this tutorial, we learned how to use the Tortoise ORM framework to implement CRUD operations, initialize the database and create models, and perform complex database queries. As we can see, Tortoise ORM makes managing databases in Python asynchronous applications very simple and intuitive.

The above is the detailed content of ORM framework Tortoise ORM in Python in practice. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles