聚合查询
整表整合
-
聚合函数(需要导入):
- 导入方法: from django.db.models import *
- 聚合函数: Sum, Avg, Count, Max ,Min
-
语法: mymodel.objects.aggregate(结果变量名=聚合函数(‘列’))
-
返回结果:结果变量名和值组成的字典,格式:{‘结果变量名’:值}
>>> from bookstore.models import Book >>> from django.db.models import Count >>> Book.objects.aggregate(res=Count('id')) {'res': 5}
分组聚合
- 语法: QuerySet.annotate(结果变量名=聚合函数(‘列’))
- 返回值: QuerySet
>>>pub_count_set = pub_set.annotate(mycount=Count('pub'))
>>> print(pub_count_set)
<QuerySet [{'pub': '清华大学出版社', 'mycount': 3}, {'pub': '机械工业出版社', 'mycount': 2}]>
原生数据库操作
Django也可以支持直接用SQL语句的方式通信数据库
查询
- 查询:使用mymodel.objects.raw()进行数据库查询操作
- 语法:mymodel.objects.raw(sql语句,拼接参数)
- 返回值:RawQuerySet集合对象【只支持基础操作,比如循环】
- 小心SQL注入
books = Book.objects.raw('select * from book where id = %s' % ('1 or 1=1')) # 攻击结果,查询所有用户信息 >>> books = Book.objects.raw('select * from book where id = %s' % ('1 or 1=1')) >>> books <RawQuerySet: select * from book where id = 1 or 1=1> >>> for i in books: ... print(i.title) ... python Django JQuery Linux HTML5 # 解决方法 books = Book.objects.raw('select * from book where id = %s', ['1 or 1=1']) >>> books = Book.objects.raw('select * from book where id = %s', ['1 or 1=1']) >>> for i in books: ... print(i.title) ... python ### 其实查询的是 id = '1 or 1=1' 但是id是int型传的是字符串,mysql自动处理查询第一个数字 即1
游标cursor
- 导入cursor所在的包 from django.db import connection
- 用创造cursor类的构造函数创建cursor对象,在使用cursor对象,为保证再出现异常是能释放cursor资源,通常使用with语句进行创建操作
from django.db import connection with connection.cursor() as cur cur.execute('SQL语句','拼接参数')