尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

AirModel实战教程:基于PostgreSQL的异步ORM轻松上手

AirModel实战教程:基于PostgreSQL的异步ORM轻松上手
📅 发布时间:2026/7/22 19:18:14

AirModel实战教程:基于PostgreSQL的异步ORM轻松上手

【免费下载链接】airThe first web framework designed for AI to write. Built on Python, FastAPI, Pydantic, and HTMX. By the authors of Two Scoops of Django.项目地址: https://gitcode.com/gh_mirrors/air23/air

AirModel是GitHub加速计划(air23/air)项目中内置的异步ORM工具,专为PostgreSQL数据库设计,让开发者能够轻松实现数据模型与数据库的交互。作为首个专为AI编写的Web框架,AirModel基于Python、FastAPI、Pydantic和HTMX构建,提供了简洁高效的数据库操作体验。

为什么选择AirModel?

AirModel作为一款现代化的异步ORM,具有以下核心优势:

  • 简单易用:只需一个导入和一个基类,就能定义数据模型并处理验证、序列化和异步数据库操作
  • 自动迁移:添加字段后,create_tables()会自动使用ALTER TABLE ADD COLUMN迁移现有表
  • Django风格API:提供create、get、filter、save、delete等直观方法
  • 类型安全:基于Pydantic构建,提供完整的类型注解和编辑器支持

快速开始:安装与配置

要使用AirModel,首先需要安装Air框架。通过以下命令克隆项目仓库:

git clone https://gitcode.com/gh_mirrors/air23/air

然后安装依赖:

cd air uv sync

配置PostgreSQL连接,只需设置环境变量:

export DATABASE_URL="postgresql://user:password@localhost/dbname?sslmode=require"

Air会在应用启动时自动打开asyncpg连接池,并在关闭时自动关闭连接池,无需手动管理连接。

定义你的第一个AirModel模型

创建数据模型非常简单,只需继承AirModel并定义字段:

from air import AirField, AirModel class UnicornSighting(AirModel): id: int = AirField(primary_key=True) name: str location: str sparkle_rating: int sighted_at: datetime

每个类型注解都会直接映射到PostgreSQL列类型:

Python类型PostgreSQL类型
intINTEGER
strTEXT
boolBOOLEAN
datetimeTIMESTAMPTZ
floatDOUBLE PRECISION

类名会自动从CamelCase转换为snake_case作为表名,符合PostgreSQL的命名习惯。

基本CRUD操作

AirModel提供了直观的API来执行常见的数据库操作:

创建记录

# 创建单条记录 sighting = await UnicornSighting.create( name="Sparkle Hoof", location="Rainbow Falls", sparkle_rating=9, sighted_at=datetime.now() ) # 批量创建记录 sightings = await UnicornSighting.bulk_create([ UnicornSighting(name="Moonbeam", location="Star Mountain", sparkle_rating=8), UnicornSighting(name="Fluffball", location="Cloud Valley", sparkle_rating=7) ])

查询记录

# 获取单条记录 sighting = await UnicornSighting.get(id=1) # 过滤记录 high_rated = await UnicornSighting.filter(sparkle_rating__gte=8) # 排序和分页 recent_sightings = await UnicornSighting.filter( location__icontains="falls" ).order_by("-sighted_at").limit(10).offset(20) # 计数 count = await UnicornSighting.count(sparkle_rating__gte=9)

更新记录

sighting = await UnicornSighting.get(id=1) sighting.sparkle_rating = 10 await sighting.save() # 批量更新 await UnicornSighting.filter(location="Rainbow Falls").update(sparkle_rating=9)

删除记录

sighting = await UnicornSighting.get(id=1) await sighting.delete() # 批量删除 await UnicornSighting.filter(sparkle_rating__lt=5).delete()

事务处理

AirModel支持事务操作,确保数据一致性:

async with app.db.transaction(): sighting1 = await UnicornSighting.create(name="Sunny", location="Meadow", sparkle_rating=8) sighting2 = await UnicornSighting.create(name="Twilight", location="Forest", sparkle_rating=9) # 如果发生异常,所有操作都会回滚

与AirForm集成

AirModel可以与AirForm无缝集成,实现表单验证和数据库操作的一体化:

from air import AirForm, AirField, AirModel class ContactMessage(AirModel): id: int = AirField(primary_key=True) name: str = AirField(..., max_length=100) email: str = AirField(..., format="email") message: str = AirField(..., widget="textarea") class ContactForm(AirForm[ContactMessage]): pass # 在请求处理中使用 async def handle_contact(request): form = await ContactForm.from_request(request) if form.is_valid(): # 直接保存到数据库 await form.data.create() return RedirectResponse("/thanks") return TemplateResponse("contact.html", {"form": form})

模型迁移

AirModel提供自动迁移功能,当你修改模型定义后,只需调用:

await app.db.create_tables()

系统会自动为每个已导入的AirModel子类创建表,并为新增字段执行ALTER TABLE ADD COLUMN操作,简化开发流程。

深入学习资源

  • 官方文档:docs/learn/airmodel.md
  • 模型源码:src/air/model/
  • 测试示例:tests/test_model.py
  • 示例项目:examples/src/models__AirModel__to_form.py

通过本教程,你已经掌握了AirModel的基本使用方法。这个强大的异步ORM工具将帮助你更高效地处理PostgreSQL数据库操作,让你能够专注于业务逻辑的实现。无论是小型项目还是大型应用,AirModel都能提供简洁、高效且类型安全的数据访问体验。

【免费下载链接】airThe first web framework designed for AI to write. Built on Python, FastAPI, Pydantic, and HTMX. By the authors of Two Scoops of Django.项目地址: https://gitcode.com/gh_mirrors/air23/air

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

相关新闻

  • 学生护眼灯买什么样的好?学生适用护眼台灯推荐,写作业更适配
  • arrow.nvim高级用户指南:分割窗口打开书签文件的技巧
  • Dioxus:三行代码开发跨平台应用,多平台支持与全栈功能助力高效开发!

最新新闻

  • 为什么选择GraPHP?PHP图论库的5大优势解析
  • 终极ASMR下载指南:如何快速获取优质音频资源
  • 2026年7月积家长春官方售后网点地址及服务热线:为客户提供权威信息 - 积家官方售后服务中心
  • 2026年7月最新美度南京溧水万达广场维修保养服务电话 - 亨得利钟表维修中心
  • 江诗丹顿中国官方售后服务中心|服务电话与网点地址权威信息通知(2026年7月更新) - 江诗丹顿服务中心
  • 南通GEO专业机构

日新闻

  • AI云原生实战05-金融AI上云最难的不是技术,是“不出事“——TCE银行风控架构拆解
  • 2026年GEOSEO优化公司选型深度测评:五大硬核标准严选,这六家重塑搜索增长新格局 - 品牌前沿专家
  • **核验!2026年7月卡地亚香港**售后网点地址及服务电话公告 - 卡地亚服务中心

周新闻

  • SaaS软件行业GEO实践:AI搜索时代的品牌可见性与获客新路径
  • 什么是PCTFE?医药高端包装的“防潮王牌“材料
  • 【JVM调优实战】16-可视化利器-JConsole-VisualVM-JMC

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号