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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
