使用django orm执行复杂查询的一些实用函数
dj-querytools的Python项目详细描述
DJ查询工具
一个函数集合,使为django项目构建聚合sql查询更容易一些
安装
pip install dj-querytools
用法
简单聚合:
假设模型如下:
class Todo(models.Model):
owner = models.CharField(max_length=30)
title = models.CharField(max_length=30)
status = models.CharField(max_length=30, choices=TODO_STATUSES)
size = models.PositiveIntegerField(default=1)
due = models.DateField()
due_time = models.DateTimeField()
group_by_and_aggregate
示例
group_by_and_aggregate(qs,'size','Sum')>>20
group_by_and_annotate
按提供的字段执行聚合和分组:
示例
result=group_by_and_annotate(qs,'status','Count')>>{'D':5,'N':1,'P':8}
as_timeseries
qs = Todo.objects.filter(owner="Jack")
as_timeseries(
qs,
'due_time',
'id',
'Count',
'2018-11-01',
'2018-11-10'
)
>> [{'x': '2018-11-01', 'y': 3.0}, {'x': '2018-11-02', 'y': 3.0}, {'x': '2018-11-03', 'y': 0}, {'x': '2018-11-04', 'y': 2.0}, {'x': '2018-11-05', 'y': 2.0}, {'x': '2018-11-06', 'y': 0}, {'x': '2018-11-07', 'y': 0}, {'x': '2018-11-08', 'y': 0}, {'x': '2018-11-09', 'y': 0}, {'x': '2018-11-10', 'y': 0}]
pivot_table
给定一个平面查询集,将其按一个或多个字段分组。
- 字段用逗号分隔
- (可选)提供序列化程序函数来序列化项(否则它将只追加queryset行)
result=pivot_table(qs,'owner,status',serialize_todo)>>{'Jack':{'N':[{'title':'Day year outside whatever int'}],'P':[{'title':'Answer society close example '},{'title':'Raise real individual general'}],'D':[{'title':'Number organization particula'},{'title':'Least activity herself than c'},{'title':'Country local pretty yourself'}]},'Jane':{'P':[{'title':'Prevent do still teacher grou'},{'title':'Include they management first'},{'title':'Number court few loss sort mu'},{'title':'That federal end local dream '},{'title':'Able ask listen. Cost ball me'},{'title':'Bad know meeting compare room'}],'D':[{'title':'Through town stay able car di'},{'title':'Tree design candidate because'}]}}
其他材料
- 有关完整功能列表,请参见
spec.txt
- 例如,检查
example_app/tests.py
贡献
更新规范:
python manage.py test --testrunner=testreporter.runner.BDDTestRunner