Django数据库操作笔记

本文介绍了如何使用 Django 的 ORM 进行 sum、count 和 avg 操作,包括具体语法示例,并展示了如何通过 connection 执行 SQL 查询,以及如何获取特定索引以优化查询。


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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值