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

ORM framework Tortoise ORM in Python in practice

WBOY
Release: 2023-06-10 18:05:58
Original
2889 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template