1.配置脚本
2.django终端打印出sql语句
3.一般查询
4.求和,求平均数,计数等
5.annotate
6.extra
1.配置脚本
# 新建一个.py文件
import os
if __name__ == ‘__main__‘:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled.settings") # 这里需要注意:1.MODULE; 2.django-project.settings
import django
django.setup()
2.django终端打印出sql语句
# settings.py
# 即为你的Django项目配置上一个名为django.db.backends的logger实例即可查看翻译后的SQL语句。
LOGGING = {
‘version‘: 1,
‘disable_existing_loggers‘: False,
‘handlers‘: {
‘console‘:{
‘level‘:‘DEBUG‘,
‘class‘:‘logging.StreamHandler‘,
},
},
‘loggers‘: {
‘django.db.backends‘: {
‘handlers‘: [‘console‘],
‘propagate‘: True,
‘level‘:‘DEBUG‘,
},
}
}
3.一般查询
from app01 import models
ret = models.Employee.objects.all().values(‘name‘, ‘dept‘)
# SELECT `employee`.`name`, `employee`.`dept` FROM `employee` LIMIT 21; args=()
4.求和,求平均数,计数等等
from app01 import models
from django.db.models import Avg,Sum,Min,Max,Count
5.annotate
from app01 import models
from django.db.models import Avg,Sum,Min,Max,Count
# annotate前面是什么,就按照什么分组。如all().annotate()就是按照id分组;values(‘age‘).annotate()就是按照年龄分组
ret = models.Employee.objects.values(‘dept‘).annotate(a=Avg(‘salary‘)).values(‘dept‘, ‘a‘)
# SELECT `employee`.`dept`, AVG(`employee`.`salary`) AS `a` FROM `employee` GROUP BY `employee`.`dept` ORDER BY NULL LIMIT 21; args=()
6.extra(添加条件:工资大于3000)
from app01 import models
ret = models.Employee.objects.all().extra(
select= {
‘gt‘: ‘salary > 3000‘
}
)
print(ret)
for i in ret:
print(i.name, i.gt)
# SELECT (salary > 3000) AS `gt`, `employee`.`id`, `employee`.`name`, `employee`.`age`, `employee`.`salary`, `employee`.`dept` FROM `employee`; args=()
# python 0 django 1 js 1
# 执行原生SQL
# 更高灵活度的方式执行原生SQL语句
from django.db import connection, connections
cursor = connection.cursor() # cursor = connections[‘default‘].cursor()
cursor.execute("""SELECT * from employee where salary > %s""", [3000]) # 也可以id=? 或salary < ?
row = cursor.fetchall()
print(row)
# SELECT * from employee where salary > 3000; args=[3000]
# ((2, ‘django‘, 20, 5000, ‘框架部‘), (3, ‘js‘, 600, 20000, ‘编程部‘))