from django.db.models import Count |
from django.db.models import Sum |
from django.db.models import Avg |
sum操作
Sales_amount.objects.values( 'staff' ).annotate(s_amount = Sum ( 'amount' )) |
count操作
2 | Members.objects.values( 'designation' ).annotate(dcount = Count( 'designation' )) |
avg操作
Book.objects.all().aggregate(Avg('price'))
use index操作, 有些查询我们希望使用某个特定的索引来提高查询效率,django官方没有提供这个功能,需要开发者打一下with-hints这个补丁
bs = Soc_task.objects.all().order_by("-id").with_hints('name_index')[0:10]
通过connection操作数据库
from django.db import connection
cursor = connection.cursor()
cursor.execute(sql_str)
row_all = cursor.fetchall()
for row in row_all
for col in row:
print col
通过connection操作数据库,以dict形式返回
from django.db import connection
cursor = connection.cursor()
cursor.execute(sql_str)
DESC = cursor.description
DATA = [dict(zip([col[0] for col in DESC], ROW)) for ROW in cursor.fetchall()]
print DATA