Django_orm腳本

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, '編程部'))
相關文章
相關標籤/搜索