Python ORM 框架介绍
ORM (Object-Relational Mapping) 是对象关系映射的简称,它允许开发者使用面向对象的方式来操作数据库,而不需要直接编写SQL语句。Python中有多个优秀的ORM框架,下面介绍几个主流的选项:
1. Django ORM
特点:
- Django框架内置的ORM
- 高度集成,开箱即用
- 自动生成数据库schema
- 强大的查询API
- 支持事务、聚合、迁移等
示例代码:
适用场景:Django项目开发,需要快速构建数据库模型from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey('Author', on_delete=models.CASCADE) published_date = models.DateField() # 查询 books = Book.objects.filter(author__name='J.K. Rowling')
2. SQLAlchemy
特点:
- Python最流行的独立ORM
- 支持多种数据库后端
- 提供两种使用方式:Core(低层SQL抽象)和ORM(高层对象抽象)
- 强大的查询构建能力
- 支持连接池、事务等高级特性
示例代码:
适用场景:需要灵活性和强大功能的项目,特别是非Django项目from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # 查询 users = session.query(User).filter(User.name == 'Alice').all()
3. Peewee
特点:
- 轻量级ORM
- 简单易用,学习曲线平缓
- 支持SQLite, MySQL和PostgreSQL
- 提供简洁的API
- 支持事务、连接池等
示例代码:
适用场景:小型项目,需要简单ORM解决方案from peewee import * db = SqliteDatabase('people.db') class Person(Model): name = CharField() birthday = DateField() class Meta: database = db db.connect() db.create_tables([Person]) # 查询 query = Person.select().where(Person.name == 'John')
4. Tortoise ORM
特点:
- 专为异步Python设计(如asyncio)
- 受Django ORM启发
- 支持PostgreSQL, MySQL和SQLite
- 支持模型继承、事务等
示例代码:
适用场景:异步Python应用(如FastAPI, aiohttp)from tortoise import fields, models from tortoise.contrib.pydantic import pydantic_model_creator class User(models.Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255) class Meta: table = "users" # 异步查询 users = await User.filter(name__icontains="john")
5. Pony ORM
特点:
- 提供自动查询优化
- 简洁的语法
- 支持自动事务管理
- 图形化数据库schema编辑器
示例代码:
适用场景:需要简洁语法和自动优化的项目from pony.orm import * db = Database() class Customer(db.Entity): name = Required(str) orders = Set("Order") db.bind('sqlite', ':memory:') db.generate_mapping(create_tables=True) @db_session def get_customers(): return select(c for c in Customer if len(c.orders) > 0)[:]
选择建议
- Django项目:使用Django ORM
- 需要最大灵活性:SQLAlchemy
- 小型/简单项目:Peewee
- 异步应用:Tortoise ORM
- 简洁语法偏好:Pony ORM
每个ORM都有其优势和适用场景,选择时应考虑项目需求、团队熟悉度和长期维护性。