Home > Article > Backend Development > ORM framework Tortoise ORM in Python in practice
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
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
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()
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)
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)
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()
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')
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!