This Is Why You Should Use Tortoise-ORM in Your Python Projects

Manage your databases like a boss!

Eldad Uzman
Better Programming

--

Image by Wolfgang Hasselmann at unsplash

Integrating relational databases into our code could be clunky, but it can be easier with ORM.

In this article, I’ll introduce you all to a cutting-edge Python ORM package called tortoise ORM and give a hands-on example.

Why ORM?

Object relational mapping maps relational database table structures into objects.

This allows us to avoid writing explicit SQL queries in our code that might be hard to read, debug and maintain.

In this simple example, we create a sqlite database called db1, and then we create a table called employees with three fields: ID, NAME, and AGE, then we insert one row into this table, commit the changes and close the connection.

Now we can view the table content in Visual Studio Code’s SQLite extension:

So, this code works but it’s terrible to maintain.

Especially when there are dozens of tables with complex relationships between them and they are constantly modified and require migrations.

Using an ORM will replace all the queries with objects and function calls will result in better organization and readability.

Why Tortoise?

The key advantage of tortoise ORM is its’ native support of asyncio.
Most other Python ORM packages require some workarounds to use it with asyncio code. With Tortoise, it happens natively!

That’s quite awesome, isn’t it?

So, let's refactor our example above to work with Tortoise and asyncio!

Now the code is infinitely more readable!

Concurrency

As stated, Tortoise ORM supports native asyncio.

Let's take advantage of it :).

So, in this example, I created 30 users, and concurrently with that, I performed a 10-second sleep (this could be any other meaningful task).

So we should expect a 300-second run time if this had been a regular sequential code.

But with concurrency, this takes just 10 seconds :)

Let's see the output:

total_time= 10.03 seconds

Now, let’s look at the table:

Great!

More Awesome Stuff!

Tortoise easily integrates to async web server frameworks (ASGI) such as fastapi, quart, or Starlette.

It can easily create pydantic models out of the ORM model at run time.

It comes with a built-in migration tool to keep track of database changes; it supports transactions, triggers (known as signals) and even routers to route queries to the different database instances.

It brings an entire toolchain to database management and manipulation and provides an awesome developer experience.

Thanks for reading. Stay tuned for more.

--

--