返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Python

The Post-Django Era: A Selection Guide for Three Async ORMs — SQLAlchemy 2.0, Tortoise, and Piccolo

SQLAlchemy 2.0 is the one that's industrial-grade stable — anyone who's used Alembic's migration capabilities knows. Tortoise ORM is the comfort zone for Django veterans, but flexibility is limited. Piccolo has modern syntax but a still-green ecosystem, better for dabbling. Stop worshipping Stars; in production, what matters is what can take a beating.

曦远 (DealiAxy)约 26 分钟
目录16 个章节

Preface

From Django's safe harbor toward the async sea of stars

— Epigraph

In my recent spare time, I've been tinkering with the TechDistill project. You may have noticed that recent WeChat official account posts have all been "AI Tech Daily" — that's a product of the TechDistill project. Amid the various kinds of tech news iterating rapidly every day, developers and tech enthusiasts often face severe information overload. TechDistill aggregates multiple high-quality tech information sources and uses LLMs (large language models) for in-depth organization and summarization, thereby greatly reducing users' mental burden of filtering and reading.

Also while developing something new, I felt the traditional Django approach was too heavy. FastAPI's approach is simple and easy to use, but I don't like this kind of piecemeal toolkit — it gives a feeling of chaos and disorder. That's when I remembered LiteStar, which I'd written about and shared before…

As a developer steeped in the Django ecosystem for many years, I've always held a certain reverence for Django's all-in-one suite: stable, complete, almost defining the standard for Python web development. But as the web enters the async era, especially after I recently got a deep experience of LiteStar, a framework that pursues extreme architecture and performance, I realized it's time to use LiteStar on some new AI-related projects. And leaving the Django ecosystem means saying goodbye to the mature, easy-to-use Django ORM.

In modern async web development, choosing an ORM (Object-Relational Mapping) is no longer something bundled free with the framework, but a deep contest concerning code cleanliness, type safety, and the ceiling of engineering.

Today, let's talk about three representative choices in the current Python async ecosystem: SQLAlchemy 2.0, Tortoise ORM, and Piccolo.

The Contenders

SQLAlchemy 2.0: The Industrial Machine Tool of the Database World

If the Python database field has a temple, the one enshrined there is surely SQLAlchemy. After a long 1.x era, the release of version 2.0 marked its formal embrace of strong type annotations and native async.

SQLAlchemy has 11.7k stars on GitHub and is the first-choice ORM in the Python ecosystem.

  • Core philosophy: Data Mapper (data mapping pattern). It decouples in-memory objects from database table structures, giving developers extremely high operational precision.
  • Killer feature: An unmatched ecosystem and the Alembic migration tool.
  • Downsides: The steepest learning curve; configuration is a bit cumbersome.

Tortoise ORM: The Gentle Haven for Django Veterans

If you're used to Django's Model.objects.filter() style, Tortoise will feel unprecedentedly familiar.

This project has also been developing for a long time now, with 5.5k+ stars on GitHub — it counts as a mature project.

  • Core philosophy: Active Record (domain model pattern). The model itself contains the data operation logic.
  • Killer feature: Zero learning cost (for Django users).
  • Downsides: Limited flexibility; it struggles a bit under large-scale complex queries.

Piccolo: A Prisma Challenger from the Future

This is a niche gem with not that many GitHub Stars (about 1.9k), but an extremely stunning design.

It has a bit of that Prisma and drizzle feel from the TypeScript ecosystem.

  • Core philosophy: Modern, lightweight, type-safety first.
  • Killer feature: Highly modern chained syntax and built-in Piccolo Admin.
  • Downsides: Smaller community ecosystem; when you hit a bug in production you may have to fight alone.

Straight to the Code

For an intuitive comparison, we designed a classic scenario: a one-to-many association query between users (User) and posts (Post).

Modeling Comparison

SQLAlchemy 2.0 mandates type annotations and is extremely IDE-friendly:

class User(Base):
    __tablename__ = "user"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(30))
    posts: Mapped[list["Post"]] = relationship(back_populates="user")

Tortoise has that familiar flavor, almost a 1:1 reproduction of Django model syntax.

class User(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=30)

Piccolo is concise to the extreme, born for async and type safety, with very modern syntax.

Model definitions inherit directly from Table

class User(Table):
    name = Varchar(length=30)

CRUD Comparison

SQLAlchemy (explicit Session pattern):

# Create
async with async_session() as session:
    session.add(User(name="Gemini"))
    await session.commit()

# Read
users = (await session.execute(select(User).where(User.name == "Gemini"))).scalars().all()

Tortoise (chained API):

If you miss Django's syntax, Tortoise was made for you. Model classes come with built-in CRUD methods.

# Create
await User.create(name="Gemini")

# Read
users = await User.filter(name="Gemini").all()

Piccolo (SQL-style chaining):

Chained calls, with syntax close to native SQL.

# Create
await User(name="Gemini").save()

# Read
users = await User.select().where(User.name == "Gemini").run()

Migration Capabilities

A good ORM can't do without excellent migration capabilities. These ORMs all have decent database migration features; see the table below for a detailed comparison.

FeatureSQLAlchemy (Alembic)Tortoise (Aerich)Piccolo (Built-in)
MaturityIndustry ceiling. Extremely stable; handles complex scenarios.Fairly good; implemented based on Alembic's ideas.Excellent; natively integrated.
FlexibilitySupports manually editing migration scripts; logic is clear.Relatively rigid; complex changes sometimes error out.High degree of automation, even with a GUI.
Multi-DB supportPerfect support for multiple databases and multiple schemas.Weaker.Average.
Core logicalembic revision --autogenerateaerich migratepiccolo migrations new

PS: Alembic is said to be a tool you can always trust. Although the initial setup is a bit complex, it can handle any weird database change requirement.

How to Choose?

To help everyone make a quick decision, I've put together this comprehensive evaluation table:

DimensionSQLAlchemy 2.0Tortoise ORMPiccolo
Industry standingAbsolute dominanceMainstream in the async worldRising star
Migration toolAlembic (industrial-grade robustness)Aerich (good enough)Built-in (excellent experience)
Admin backendSQLAdmin (third-party required)Community pluginsBuilt-in (very high visual appeal)
Type checking⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Project ceilingThe ceiling for handling complex SQLSuited to small-to-medium businessSuited to independent developers

Other Key Considerations

Type Hinting

  • SQLAlchemy 2.0: Through the Mapped type, the IDE can achieve true point-and-click (autocompletion), extremely friendly for developing large projects.
  • Piccolo: Native type safety; no extra Mypy plugin needed.
  • Tortoise: Although supported, type inference can break under certain dynamic queries.

Performance and Speed

  • SQLAlchemy: After 20 years of optimization, performance is very strong when handling large amounts of data.
  • Piccolo: Uses an extremely lightweight underlying implementation; on simple CRUD it is usually faster than SQLAlchemy.
  • Tortoise: Because it mimics Django with many layers of wrapping, performance is relatively the slowest of the three (though not strongly noticeable in ordinary applications).

Ecosystem

  • SQLAlchemy: Unmatched. Almost all third-party tools (admin, encryption, geospatial) will support it first.
  • Piccolo: Has its own Piccolo Admin, but fewer other ecosystem plugins.

Pitfall Guide

  1. The myth of Star counts: Never blindly worship Stars. Piccolo is good, but 1.9k Stars means its ecosystem breadth is insufficient. If you're building a project involving tens of millions in funds, or one that needs complex database migrations, you must choose SQLAlchemy. Those 11.7k Stars buy you the tens of thousands of StackOverflow answers you can search when fixing bugs late at night.
  2. The obsession with migrations: For web projects, the stability of the migration tool is above all else. Although Alembic is a bit more troublesome to configure, its ability to handle complex scenarios like changing field types and multi-database sync is something other native tools can hardly match.
  3. The temptation of Admin: Piccolo Admin is genuinely slick, very much like the modern tools in the TypeScript ecosystem similar to Prisma and drizzle. But don't forget that SQLAlchemy's rich ecosystem also has similar admin interfaces, and an admin interface is only for debugging during local development — real delivery still requires building a real admin backend.

Wrap-up

For some new projects I've been wanting to do recently, I plan to try the LiteStar + SQLAlchemy 2.0 + Alembic combination, and I'll continue sharing the development experience then.

Since we've already left Django's comfort zone, don't go looking for another Django ORM substitute. Embrace SQLAlchemy's Data Mapper pattern. Although it's hard work up front, the code decoupling and command over complex business it brings make it all worthwhile.

I'm also quite optimistic about Piccolo, but the ecosystem doesn't seem mature enough yet — I'll keep watching for now.

_EOF_

The Post-Django Era: A Selection Guide for Three Async ORMs — SQLAlchemy 2.0, Tortoise, and Piccolo

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

python实现解析markdown文档中的图片,并且保存到本地~

背景 前阵子简书好像说是凉了,搞得我有点小慌,毕竟我的大部分博客都是放在简书上面的,虽然简书提供了打包导出功能,但是只能导出文字,图片的话还是存在简书服务器上面,再加上我一直想要重新做一个个人博客,于是就有了这篇文章。 思路 首先是要解析markdown文档,然后获取到其中的所有图片,再把图片按md文件分好目录保存。 解析markdown文档 这里我用了misaka模块,据说是python的mar

2021-12-18 · Python · 约 1 分钟

使用Python+FFMPEG实现视频分割与合并

前言 日常中偶尔会遇到需要简单剪辑处理视频的场景,以前我可能会拿出PR来剪辑一下,(别跟我说国产那些软件,剪辑完视频强制加上广告片头片尾恶心的一批),但是PR毕竟太重量级,剪个简单的视频都要花不少时间,直到我发现了FFmpeg…… 这个FFmpeg真的是神器,免费开源功能强大,好像很多软件都是基于这个开发的,它本身提供了命令行接口就已经能满足我们日常的简单视频处理需求,我用来简单处理视频分割、合并

2022-05-27 · Python · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…