Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/shaopson/ormlite
一个简单的Python ORM,支持sqlite3 mysql, 具有延迟查询,链式查询等功能; This is a simple ORM, support sqlite3,mysql
https://github.com/shaopson/ormlite
orm python3
Last synced: about 1 month ago
JSON representation
一个简单的Python ORM,支持sqlite3 mysql, 具有延迟查询,链式查询等功能; This is a simple ORM, support sqlite3,mysql
- Host: GitHub
- URL: https://github.com/shaopson/ormlite
- Owner: shaopson
- Created: 2019-04-18T12:16:09.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-03-16T09:28:04.000Z (almost 5 years ago)
- Last Synced: 2023-10-21T11:38:27.197Z (about 1 year ago)
- Topics: orm, python3
- Language: Python
- Homepage:
- Size: 134 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ORMlite
一个简单的Python ORM,支持sqlite3 mysql, 具有延迟查询,链式查询等功能
接口模仿了Django的ORM框架 和Django ORM一样简单,易用,ORMlite不支持迁移功能(migrate)### 快速上手
如果你使用过Django的ORM,那么你会感觉非常熟悉创建model,使用sqlite3
```python
import ormlite
from ormlite import configuration
from ormlite.db.utils import create_tables#设置数据库
configuration.conf_db({
"ENGINE":"ormlite.db.sqlite3",
"NAME":"db.sqlite3",
})
#开启Debug 查询时显示生成的sql语句
configuration.debug = True#定义Model
class User(ormlite.Model):
id = ormlite.PrimaryKey()
name = ormlite.CharField(max_length=50)
sex = ormlite.CharField(max_length=1)
birthday = ormlite.DateField()#创建
create_tables([User,],configuration.db)
```创建对象
```python
import datetime
user = User(name='test',sex='M',birthday=datetime.datetime(2020,1,1).date())
user.save()
```简单查询
```python
#返回单个User实例
user = User.object.get(id=1)#获取全部User实例
users = User.object.all()#查询所有id大于10的实例
# ge:>=, gt:>, le:<=, lt:<
users = User.object.query(id__gt=10)#排除所有id大于10的实例
users = User.object.exclude(id__gt=10)#排序
users = User.object.all().sort('id')#正序
users = User.object.all().sort('-id')#反序#切片
users = User.object.all()[2:4]
#第一个
user = User.object.all().first()
#最后一个
user = User.object.all().last()#计数
count = User.object.all().count()#只查询某个字段(结果以键值对的格式返回)
names = User.object.all().values('name')
##只查询某个字段(结果以列表的格式返回)
names = User.object.all().items('name')
##列表降维
names = User.object.all().items('name',flat=True)
##数据聚合
from ormlite.query import Count,Min,Max,Sum,Avg
result = User.object.all().values(count=Count('id'))
##分组计算
result = User.object.all().values(count=Count('name')).group('name')
#[{'name': 'aa', 'count': 1}, {'name': 'bb', 'count': 1}, {'name': 'cc', 'count': 1}]
```###数据库配置
####sqlite3
```
from ormlite import configuration
configuration.conf_db({
"ENGINE":"ormlite.db.sqlite3",
"NAME":"db.sqlite3",
})
```####mysql
当使用mysql时,需要安装mysql-connector
```
from ormlite import configuration
configuration.conf_db({
"ENGINE":"ormlite.db.mysql",
'NAME': 'ormlite',
'USER': 'root',
'PASSWORD': 'ormlite',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'autocommit': True,
}
})
```