标签:not 交换 遍历 load middle 计算 ever code 页面
上课第18天,打卡:
《晚风》 - 伍佰
################
# 2017-08-27 - 课上笔记
################
‘‘‘
ORM
Book.objects.get(id=2) 拿到一个元素
Book.objects.filter(id=2) 拿到一个集合
数据添加
class Book(models.Model):
pass
class Publisher(models.Model):
pass
class Author(models.Model):
pass
1.单表添加数据:
- Book.objects.create(xxx)
- book_obj = Book(xxx)
book_obj.save()
2.一对多添加:
> 外键建在子表上(一对多的多的那个表上)
class Book(models.Model):
...
publisher = models.ForeignKey("Publisher")
...
一对多添加方式1:
Book.objects.create(xxx=xxx,publisher_id=1)
一对多添加方式2:
pulisher_obj = Publisher.objects.get(id=1)
book_obj = Book(xxx=xxx)
book_obj.publisher = pulisher_obj
book_obj.save()
3.多对多添加:
取决于第三张表是自己创建的还是Django创建的
> 以Django创建第三张表为例:
class Book(models.Model):
...
publisher = models.ForeignKey("Publisher")
authors = models.ManyToManyField("Author")
...
author_list = Author.objects.all()
book_obj = Book.objects.get(id=1)
book_obj.authors.add(*author_list)
book_obj.authors.remove(*author_list) # 清空author_list列表里指定的关系
book_obj.authors.clear() # 清空全部跟book_obj相关的关系
> 以自己手动创建第三张表为例:
class Book(models.Model):
...
publisher = models.ForeignKey("Publisher")
# authors = models.ManyToManyField("Author")
...
class Book2Author(models.Model):
book = models.ForeignKey("Book")
author = models.ForeignKey("Author")
Book2Author.objects.create(book=book_obj,author=author_obj)
或者
Book2Author.objects.create(book_id=1,author_id=1)
单表查询
表.objects.all() ----> QuerySet集合对象 [obj1,obj2,obj3...] 记录的集合
表.objects.filter() ----> QuerySet集合对象
表.objects.get() ----> model对象 obj 当前操作表的一条记录
QuerySet.first() ----> model对象 例如:表.objects.all().first()
QuerySet.last()
QuerySet.count()
value
Book.objects.value("title") ---> QuerySet集合:[{‘title‘:‘python‘},{‘title‘:‘linux‘},{‘title‘:‘c++‘}]
Book.objects.value("title","price")
Book.objects.value_list("title") ---> 数据类型不一样,不再是字典而是元组
exclude 排除
order_by
reverse
distinct 去重
万能的 ‘__‘
表.objects.filter(字段__keyword)
keyword:
lt
gt
in
exclude 即 not in
contains
icontains
range
exists
万能的 ‘__‘ 之单表查询示例:
Book.objects.filter(id__gt=2).values("title") ---> 拿到id大于2的书籍的名字
Book.objects.filter(name_contains=‘python‘).values("title") 模糊匹配
Book.objects.filter(name_icontains=‘python‘).values("title") 不区分大小写
models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
models.Tb1.objects.filter(name__contains="ven") # 模糊匹配
models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
startswith,istartswith, endswith, iendswith,
多表查询(关联查询)
SQL:
- 子查询方式:select name from dep where id=(select dep_id from emp where name=‘张三‘);
- 联表查询方式:select dep.name from emp left join dep on emp.dep_id=dep.id where emp.name=‘张三‘;
ORM的关联查询:
- 通过对象
拿到对象集合,然后遍历对象,拿到对象.字段属性
book_obj = Book.objects.get(title=‘python‘)
author_list = book_obj.authors.all()
for author in author_list:
print author.name
- 通过 ‘__‘ 的方式
单表:查询Python这本书的价格
Book.objects.filter(title=‘python‘) # 取出了QuerySet集合
ret = Book.objects.filter(title=‘python‘).values(‘price‘)
多表:查询Python这本书的出版社的邮箱
Book.objects.filter(title=‘python‘).values(‘publisher__email‘)
publisher 是Book的外键字段
__
email 是Publisher的email字段
查询Python这本书所有的作者名字
Book.objects.filter(title=‘python‘).values(‘authors__name‘)
查询alex出版过的所有书的名字
Book.objects.filter(authors__name=‘alex‘).values(‘title‘) ####正向查询####
Author.objects.filter(name=‘alex‘).values(‘book_title‘) ####反向查找####
### 正向查用字段,反向查用表名 ###
# 正向查找 - 查找出版过Python这本书的出版社的名字
Book.objects.filter(title=‘python‘).values(‘publisher__name‘)
# 反向查找 - 查找出版过Python这本书的出版社的名字
Publisher.objects.filter(book_title=‘python‘).values("name")
聚合和分组查询:
SQL:
聚合函数:max min count avg sum
每一个部门有多少员工?
select * from emp group by 部门字段
求所有书籍的价格平均值
select AVG(‘price‘) from book;
Django:
aggregate 通过对QuerySet进行计算,返回一个聚合值的字典
求所有书籍的价格平均值
from django.db.models import Avg,Min,Sum,Max
Book.objects.all().aggregate(Avg(‘price‘));
Book.objects.all().aggregate(PriceAvg=Avg(‘price‘)); # {‘PriceAvg‘:100}
Book.objects.all().aggregate(PriceAvg=Avg(‘price‘),MaxPrice=Max("price"));
annotate 可以通过计算查询结果中每一个对象所关联的对象集合,从而得出总计值(也可以是平均值或总和),即为查询集的每一项生成聚合。
> 按照 group by 进行理解
查询oldboy出过的书的总价格
Book.objects.filter(authors__name="oldboy").aggregate(Sum("price"));
查每一个作者出过的书的总价格 涉及到分组 -> values("authors__name")
Book.objects.values("authors__name").annotate(Sum("price"))
按部门分组,计算每个部门有多少人:
- SQL : select count(*) from emp groupp by dep;
- ORM : Book.objects.values("dep").annotate(Count(*))
每本书的价格提高100块钱:
update book set price=price+100;
F查询与Q查询
F 使用查询条件的值,专门取对象中某列值的操作
每本书的价格提高100块钱:
from django.db.models import F
Book.objects.update(price=F("price")+100)
Q 构建搜索条件
逻辑与 &
逻辑或 |
逻辑非 ~
from django.db.models import Q
查找书名以 ‘p‘ 或者 ‘L‘ 开头的书籍:
Book.objects.filter(
Q(title__startswith=‘p‘) | Q(title__startswith=‘L‘)
)
查找书名以 ‘P‘ 开头但是不是在2005年出版的书籍:
Q(title__startswith=‘P‘) | ~Q(pub_date__year=2005)
查找以 ‘P‘ 开头并且出版时间是 2005.5.2 或者 2005.5.6 :
Book.objects.get(
Q(title__startswith=‘P‘),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
SELECT * from book WHERE title LIKE ‘P%‘ AND (pub_date = ‘2005-05-02‘ OR pub_date = ‘2005-05-06‘);
修改
QuerySet.update()
update是对QuerySet集合的操作
models对象是不能使用的
Book.objects.filter(id__gt=10).update()
Book.objects.get(id=10).update() 错误
删除
QuerySet.delete()
Json简介
Json是一种轻量级的数据交换格式
Json(JavaScript Object Notation, JS 对象标记)
Json字符串 : 符合Json规范的字符串
Json对象 : 符合Json规范的对象
JS 支持比较宽泛:
d1={"name":"alex"}
d2={‘name‘:"alvin"}
d3={name:"egon"}
Json 不支持单引号
s="hello" Json对象
s1=‘hello‘ 不是Json对象
Json是JS的一个子集
Json数据类型:
数字
字符串
布尔
数组
对象
null
Json.parse() --> 用于将一个 JSON字符串转换为 JavaScript对象
var ret = Json.parse(‘[11,22,33]‘)
var ret2 = Json.parse(‘{"name","gypsy"}‘)
Json.stringify() --> 用于将 JavaScript对象转换成 JSON字符串
Json.stringify({name:"gypsy"})
Ajax (Asynchronous Javascript And XML)
即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML)。
- 异步交互
- 局部刷新
参考:
http://www.cnblogs.com/yuanchenqi/articles/7429279.html
http://www.cnblogs.com/yuanchenqi/articles/5997456.html
http://www.cnblogs.com/yuanchenqi/articles/5997456.html
实现ajax:
- Jquery(兼容了大多数浏览器)
形式1:
$.ajax({settings})
形式2:
$.ajax(url,[settings])
- JS
$.ajax({
url:"/sendAjax/",
type:"POST",
data:{"user":$("#user").val(),"pass":$("#pass").val()}
success:function(data){
dic = JSON.parse(data);
if (dic["flag"]){
alert("OK");
}
else{
alert("ERR");
}
}
})
鼠标移出input框
$("#user").blur(function(){
alert("xxx");
});
# 用户输入名后判断是否存在该用户名
$("#user").blur(function(){
$.ajaxSetup({
data: {csrfmiddlewaretoken: ‘{{ csrf_token }}‘ },
});
$.ajax("/path/",{
type:"POST",
data:{"user":$(this).val()},
success:function(data){ // data是server返回的数据
dic = JSON.parse(data);
if(dic["flag"]){
alert("该用户名已存在!");
var $span = $("<span>");
$span.text("该用户名已存在!");
$("#user").after($span);
}
else{
alert("ok");
}
}
})
});
------------------------------------------------------------------------------------
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static ‘JS/jquery-3.1.1.js‘ %}"></script>
</head>
<body>
<button class="send_Ajax">send_Ajax</button>
<script>
//$.ajax的两种使用方式:
//$.ajax(settings);
//$.ajax(url,[settings]);
$(".send_Ajax").click(function(){
$.ajax({
url:"/handle_Ajax/",
type:"POST",
data:{username:"Yuan",password:123},
success:function(data){
alert(data)
},
//=================== error============
error: function (jqXHR, textStatus, err) {
// jqXHR: jQuery增强的xhr
// textStatus: 请求完成状态
// err: 底层通过throw抛出的异常对象,值与错误类型有关
console.log(arguments);
},
//=================== complete============
complete: function (jqXHR, textStatus) {
// jqXHR: jQuery增强的xhr
// textStatus: 请求完成状态 success | error
console.log(‘statusCode: %d, statusText: %s‘, jqXHR.status, jqXHR.statusText);
console.log(‘textStatus: %s‘, textStatus);
},
//=================== statusCode============
statusCode: {
‘403‘: function (jqXHR, textStatus, err) {
console.log(arguments); //注意:后端模拟errror方式:HttpResponse.status_code=500
},
‘400‘: function () {
}
}
})
})
</script>
</body>
</html>
import json
def index(request):
return render(request,"index.html")
def handle_Ajax(request):
username=request.POST.get("username")
password=request.POST.get("password")
print(username,password)
return HttpResponse(json.dumps("Error Data!"))
------------------------------------------------------------------------------------
cookie 和 session
参考:
http://www.cnblogs.com/yuanchenqi/articles/7439088.html
cookie 本质就是一个字典 {key:value, ...}
‘‘‘
‘‘‘
防止跨站请求伪造
$.ajaxSetup({
data: {csrfmiddlewaretoken: ‘{{ csrf_token }}‘ },
});
防止从其他网站提交post请求
{% csrf_token %}
如果之前浏览过这个网站,这个中间件就会给client一个 key-value
之后再提交POST请求的时候会带着这个 key-value
‘‘‘
‘‘‘
class Book(models.Model):
title=models.CharField(max_length=32)
price=models.DecimalFeld(max_digits=7,decimal_places=2)
批量导入数据:
def index()request:
book_list = []
for i in range(100):
book_list.append(Book(title=))
分页器
‘‘‘
‘‘‘
作业
- 图书馆里改成多表的关系
可以选多个作者
没有则跳转到添加作业页面
- 批量导入数据,分页展示
前五后五
前后禁用
- ajax异步交互+局部刷新
书籍的增删改查全部用ajaxs重写
‘‘‘
代码实现:
asas
标签:not 交换 遍历 load middle 计算 ever code 页面
原文地址:http://www.cnblogs.com/standby/p/7450649.html