上期內容回顧
# 聚合查詢
max min sum avg count
# 查詢關鍵字:aggregate
from django.db.models import Max, Min, Sum, Avg, Count
res = Book.objects.aggregate(max_price=Max('price'), )
# 分組查詢
group by
"""
默認情況下,分組之后依然可以查詢到所有的字段數據,如果設置為了嚴格模式,只能獲取到分組的那個字段
show variables like '%mode%' sql_mode='only_full_group_by';
1. group_concat
2. concat
3. concat_ws
"""
# 查詢關鍵字:annotate
res = Book.objects.annotate() # 代表的是按照models后面的表進行分組
res = Book.objects.values('title', 'price').annotate() # 執行某一個字段分組
1. 面試相關
2. 事務的四大特性:ACID
3. 事務的隔離級別
4. 事務的作用:就是保證數據的安全
5. 三個關鍵字:
start transaction;
commit;
rollback;
# 對于一些字段可以完全列舉完的可能性使用
class User:
gender_choices = (
(1, '男'),
(2, '女'),
(3, '其他'),
)
gender = models.IntergerField(choices=gender_choices)
# 獲取值
res.gender
res.get_字段名_display()
1. 全自動
2. 半自動
3. 純手動
# 特性:
異步提交
局部刷新
# 我們學習直接使用jquery封裝之后的ajax 必須引入jquery
# 在js代碼里書寫以下代碼
$.ajax({
url:'' # 提交地址
type:'post' # 請求方式
data: {'d1':d1},
dataType:'json'
success:function(res) {
console.log(res)
}
})
# 后端返回的數據格式分兩種:
1. json字符串
前端處理:
1.1 反序列化: JSON.parse(res)
1.2 在加一個參數:dataType:'json'
2. json對象
# 前端不需要做任何處理
今日內容概要
- ajax發送json格式的數據
- ajax發送文件數據
- ajax集合layer彈窗實現刪除的二次確認(了解見視頻)
- django自帶的序列化組件(了解)
內容詳細
1. ajax 發送 json格式的數據
# ajax默認提交的數據格式是 urlencoded
發送的數據類型和數據格式要保持一致
# 在views.py文件中:
from django.shortcuts import render
# Create your views here.
def index(request):
# print(request.POST)
# print(request.GET)
# print(request.FILES)
if request.is_ajax():
print(request.body) # b'{"d1":"aaa"}' bytes類型
json_bytes = request.body
json_str = json_bytes.decode('utf8') # 解碼
print(json_str, type(json_str)) # {"d1":"aaa"} <class 'str'>
import json
json = json.loads(json_str)
print(json, type(json)) # {'d1': 'aaa'} <class 'dict'>
return render(request, 'index.html')
# 在urls.py添加路由:
url(r'^index/', views.index),
# 新建index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button class="btn btn-success">發送json數據</button>
<script>
$('.btn').click(function () {
$.ajax({
url: '',
type: 'post',
data: JSON.stringify({'d1': 'aaa'}), // 序列化 json
contentType: 'application/json', // 代表發送的數據是json格式
success: function (res) {
console.log(res)
}
})
})
</script>
</body>
</html>

2. ajax發送文件數據
# 在views.py文件中添加功能:
def upload_file(request):
if request.method == 'POST':
print(request.POST)
print(request.FILES)
return render(request, 'upload.html')
# 在urls.py添加路由:
url(r'^upload_file/', views.upload_file),
# 新建upload.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="username">
<input type="text" id="password">
<input type="file" id="myfile">
<button class="btn btn-success">發送文件</button>
<script>
$('.btn').click(function () {
// ajsx上傳文件需要借助與FormData
// 1.實例化FormData
var obj = new FormData()
// 增加數據
obj.append('username', $('#username').val());
obj.append('username', $('#password').val());
// 增加文件數據
obj.append('myfile', $("#myfile")[0].files[0])
$.ajax({
url: '',
type: 'post',
data: obj, // 序列化 json
contentType: false, // 告訴瀏覽器不要修改提交的數據格式
processData: false, // 告訴瀏覽器不要對提交的數據進行任何更改
success: function (res) {
console.log(res)
}
})
})
</script>
</body>
</html>


3. django自帶的序列化器(了解)
# 在views.py中:
from app01 import models
from django.core import serializers
def user_list(request):
user_list = models.User.objects.all() # 返回 queryset類型
res = serializers.serialize('json', user_list)
return HttpResponse(res)
