class Book(models.Model):
title=models.CharField(max_length=32)
# 書籍與出版社: 一對多
publisher=models.ForeignKey(to="Publish",to_field="id") # 與這本書關聯的出版社對象,因為是一對多的關系,所以,出版社對象只能有一個。
# 書籍與作者: 多對多
authors=models.ManyToManyField("Author")
class Publish(models.Model):
name=models.CharField(max_length=32)
class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
tel=models.CharField(max_length=32)
單表操作:
1、添加
(1) 表.objects.create(**kwargs)
(2) obj=表(**kwargs)
obj.save()
1 模板語法:
(1) 自定義過濾器和標簽
(2) 模板繼承 :
base.html {% block %} {%end block%}
index(繼承母版): extend "base.html" {% block %} {%end block%}
2 ORM跨表添加
ORM一對多的添加
1、
publish_obj=Publish.objects.get(id=2)
表.objects.create(title="python",publisher=publish_obj)
2、
表.objects.create(title="python",publisher_id=2)
ORM多對多的添加
authors=models.ManyToManyField("Author") # 與這本書關聯的作者對象集合
views:
def add(request):
if request.method == "POST":
book_obj=models.Book.objects.create(title=title,...,pulisher_id=publish_id)
綁定作者關系錯誤方法:
alex_id=models.Author.objects.get(name="alex").id
egon_id=models.Author.objects.get(name="egon").id
表.objects.create(book_id=book_obj.id,author_id=alex_id)
不能直接在第三張表中插入記錄,因為沒有第三張表名
authors字段:與這本書關聯的作者對象集合
book_obj.authors.all() QuerySet
alex=models.Author.objects.get(name="alex")
book_obj.authors.add(alex,egon)
class Author():
def __str__(self):
return self.name+" "+str(self.age)
解除綁定關系
book_obj=models.Book.objects.get(nid=14)
alex=models.Author.get(name="alex")
book_obj.autors.remove(alex)
author_list=models.Author.objects.filter(id__gt=1)
book_obj.authors.remove(*author_list)
book_obj.authors.clear() 清空
綁定關系
book_obj.authors.add(obj,obj2,...)
book_obj.authors.add(*[])
解除關系
book_obj.authors.remove(obj,obj2,...)
book_obj.authors.remove(*[])
book_obj.authors.clear()
3 ORM跨表查詢(1 基於對象 2 基於雙下划線)
#####基於對象的跨表查詢
###########################################一對多跨表查詢########################
# 正向查詢: 按字段
# 查詢 python這本書的出版社的名稱和地址
# book_python=models.Book.objects.filter(title="python").first()
#
# print(book_python.title)
# print(book_python.price)
#
# print(book_python.publisher) # Publish object : 與這本書關聯的出版社的對象
# print(book_python.publisher.name)
# print(book_python.publisher.addr)
# 反向查詢:按關聯的表名(小寫)_set
# 查詢人民出版社出版過的所有書籍名稱及價格
# pub_obj=models.Publish.objects.get(name="renmin")
# book_list=pub_obj.book_set.all() # QuerySet 與這個出版社關聯的所有書籍對象
#
# for obj in book_list:
# print(obj.title,obj.price)
###########################################一對一查詢########################
# 正向查詢: 按字段
# 查詢addr在沙河的作者
authorDetail=models.AuthorDetail.objects.get(addr="shahe")
print(authorDetail.author.name) # alex
# 反向查詢:按 表名(小寫)
# 查詢 alex混跡在哪里
alex=models.Author.objects.get(name="alex")
print(alex.authordetail.addr) # shahe
###########################################多對多查詢########################
# 多對多的正向 查詢: 按字段
# 查詢 python這本書的所有作者的姓名和年齡
# book_python=models.Book.objects.get(title="python")
# author_list=book_python.authors.all()
# for obj in author_list:
# print(obj.name,obj.age)
#
# book_pythons = models.Book.objects.filter(title="python")
# for book_python in book_pythons:
# author_list = book_python.authors.all()
# for obj in author_list:
# print(obj.name, obj.age)
# 多對多的反向查詢 按關聯的表名(小寫)_set
# alex出版過的所有書籍的明顯名稱
# alex=models.Author.objects.get(name="alex")
# book_list=alex.book_set.all()
# for i in book_list:
# print(i.title,i.price)
一對一關系:
class AuthorDetail(models.Model):
addr=models.charFiled(max_length=32)
author=models.OneToOneFiled("Author")
數據庫遷移
一對一查詢:
alex的addr
author_obj=models.Author.objects.get(name="alex")
author_obj.AuthorDetail.addr
查詢在沙河的作者
author_obj=models.AuthorDetail.objects.get(addr="shahe")
print(author_obj.author.name)
#####基於雙下划線的跨表查詢
JS:
var eles_p=document.getElementByTagName("p"); [p1,p2,p3,p4,p5]
for(var i=0;i<eles_p.length;i++){
eles_p[i].style.color="red"
}
jquery:
$("p").css("color","red")
正向查詢:按字段
反向查詢:按表名
# 查詢 python這本書的價格
ret=models.Book.objects.filter(title="python").values("price","title")
print(ret) # <QuerySet [{'price': Decimal('122.00')}]>
#查詢python這本書的出版社的名稱和地址
# 正向查詢 按字段 基於book表
# ret2=models.Book.objects.filter(title="python").values_list("publisher__name")
# print(ret2)
#
# # 反向查詢 按表名 if 設置了related_name: 按設置值
# ret3=models.Publish.objects.filter(bookList__price=333).values_list("name","addr").distinct()
# print(ret3)
# 查詢人民出版社出版過的所有書籍名稱及價格
# ret4=models.Book.objects.filter(publisher__name="renmin").values("title","price")
# print(ret4.count())
# ret5=models.Publish.objects.filter(name="renmin").values("bookList__title","bookList__price")
# print(ret5.count())
#查詢egon出過的所有書籍的名字(多對多)
# ret6=models.Author.objects.filter(name="egon").values_list("book__title")
# print(ret6)
# ret7=models.Book.objects.filter(authors__name__contains="eg").values("title")
# print(ret7)
# 地址以沙河開頭的的作者出版過的所有書籍名稱以及出版社名稱
# ret8=models.Book.objects.filter(authors__authordetail__addr__startswith="sha").values("title","publisher__name")
# print(ret8)
sql與ORM:
SELECT `app01_publish`.`name`
FROM `app01_book`
INNER JOIN `app01_publish`
ON (`app01_book`.`publisher_id` = `app01_publish`.`id`)
WHERE `app01_book`.`title` = 'python'
LIMIT 21;
SELECT `app01_publish`.`name`
FROM `app01_publish` INNER JOIN `app01_book`
ON (`app01_publish`.`id` = `app01_book`.`publisher_id`)
WHERE `app01_book`.`title` = 'python'
LIMIT 21;
4 回顧聚合與分組
1 聚合函數 SUM AVG MIN MAX COUNT
2 聚合函數可以單獨使用,不一定要和分組配合使用;只不過聚合函數與group by 搭配
3 統計每一個部門有多少人: select COUNT(name) from emp group by dep_id
select book.id ,book.title,count(1) from book join bookAuthor on book.id=bookAuthor.book_id group by book.id,book.title,
def juheJquery(request):
from django.db.models import Avg,Count,Sum,Min,Max
# 單純聚合函數
# 計算所有圖書的平均價格
# ret=models.Book.objects.all().aggregate(priceSum=Sum("price"))
# print(ret) # {'priceSum': Decimal('2158.00')}
# 統計每一本書的作者個數
# ret2=models.Book.objects.all().annotate(authors_num=Count("authors")) # QuerySet
# print(ret2) # [book_obj1,book_obj2,book_obj3,book_obj4,....]
#
# for obj in ret2:
# print(obj.nid,obj.title,obj.authors_num)
# 查詢每一個出版社出版過的所有書籍的總價格
#方式1:
# ret3=models.Publish.objects.all().annotate(priceSum=Sum("bookList__price"))
#
# for obj in ret3:
# print(obj.id,obj.name,obj.priceSum)
# ret4 = models.Publish.objects.all().annotate(priceSum=Sum("bookList__price")).values("name","priceSum")
# print(ret4)
# 方式2:
# ret5=models.Book.objects.all().values("publisher__name").annotate(priceSum=Sum("price")).values("publisher__name","priceSum")
# print(ret5)
5 F與Q查詢
F查詢
class Book:read_num=models.IntegerField(default=0)
comment_num=models.IntegerField(default=0)
數據庫遷移
def fqQuery(request):
return HttpResponse("OK")
ret1=models.Book.objects.filter(comment_num__gt=50)
from django.db.models import F,Q
#查詢評論數大於閱讀數
models.Book.objects.filter(comment_num__gt=F("read_num"))
#查詢評論數大於閱讀數2倍
models.Book.objects.filter(comment_num__gt=F("read_num")*2)
models.Book.objects.all().update(price=F(price)+10)
Q查詢
from django.db.models import Q
models.Book.objects.filter(Q(comment_num)__gt=50|Q(read_num)__gt=50) 或的關系
models.Book.objects.filter(Q(comment_num)__gt=50&Q(read_num)__gt=50) 且的關系
models.Book.objects.filter(comment_num__gt=50,read_num__gt=50) 不加Q,且的關系
注:Q與,混用時,Q對象必須在關鍵字前面
============================================
ORM修改
1 obj.name="egon" obj.save() 效率低
2 表.objects.all().update(name="") 推薦
注意點:update方法是QuerySet數據類型的方法。model對象不能調用。
ORM刪除
表.objects.filter().delete()
注意事項:
1 、 delete()是QuerySet數據類型的方法
2 、 級聯刪除
網頁版實現關注點記錄:
urls: url(r'^del/(\d+)', views.delete),
def add(request):
if request.method == "POST":
titles = request.POST.get("title")
pubdate = request.POST.get("pubdate")
price = request.POST.get("price")
publish_id = request.POST.get("publish")
# 一對多 添加數據 方式1
# publish_obj=models.Publish.objects.get(name="renmin")
# book_obj=models.Book.objects.create(title=title,price=price,pubDate=pubDate,publisher=publish_obj)
# 一對多 添加數據 方式2
book_obj=models.Book.objects.create(title=titles,price=price,pubDate=pubdate,publisher_id=publish_id)
#多對多綁定關系
authors_id=request.POST.getlist("authors")
authorList=models.Author.objects.filter(id__in=authors_id)
book_obj.authors.add(*authorList)
return redirect("/index/")
publish_list=models.Publish.objects.all()
authors=models.Author.objects.all()
return render(request,"add.html",{"publish_list":publish_list,"authors":authors})
def delete(request,id):
models.Book.objects.get(id=id).authors.clear()
models.Book.objects.filter(id=id).delete()
return redirect("/index/")
def edit(request,id):
if request.method == "POST":
titles = request.POST.get("title")
pubdate = request.POST.get("pubdate")
price = request.POST.get("price")
publish_id = request.POST.get("publish")
# 一對多 添加數據 方式1
# publish_obj=models.Publish.objects.get(name="renmin")
# book_obj=models.Book.objects.create(title=title,price=price,pubDate=pubDate,publisher=publish_obj)
# 一對多 添加數據 方式2
# book_obj = models.Book.objects.get(id=id)
models.Book.objects.filter(id=id).update(title=titles, price=price, pubDate=pubdate, publisher_id=publish_id)
# 多對多解除綁定關系
models.Book.objects.get(id=id).authors.clear()
#多對多綁定關系
authors_id = request.POST.getlist("authors")
authorList = models.Author.objects.filter(id__in=authors_id)
models.Book.objects.get(id=id).authors.add(*authorList)
return redirect("/index/")
book_obj=models.Book.objects.get(id=id)
publish_list=models.Publish.objects.all()
authors=models.Author.objects.all()
return render(request,"edit.html",{"book_obj":book_obj,"publish_list":publish_list,"authors":authors})
templates:
index.html:
<td>{{ book_obj.publisher.name }}</td>
<td>
{% for author in book_obj.authors.all %}
{{ author.name }}
{% endfor %}
</td>
<td>
<a href="/edit/{{ book_obj.id }}"><button class="btn btn-info">編輯</button></a>
<a href="/del/{{ book_obj.id }}"><button class="btn btn-danger">刪除</button></a>
</td>
add.html:
<div class="form-group">
<label for="publish">出版社
<select name="publish" id="publish">
{% for publish in publish_list %}
<option value="{{ publish.id }}">{{ publish.name }}</option>
{% endfor %}
</select>
</label>
</div>
<div class="form-group">
<label for="authors">作者
<select name="authors" id="authors" multiple size="3">
{% for author in authors %}
<option value="{{ author.id }}">{{ author.name }}</option>
{% endfor %}
</select>
</label>
</div>
edit.html:
<div class="form-group">
<label for="publish">出版社
<select name="publish" id="publish">
{% for publish in publish_list %}
{% if book_obj.publisher == publish %}
<option value="{{ publish.id }}" selected="True">{{ publish.name }}</option>
{% else %}
<option value="{{ publish.id }}">{{ publish.name }}</option>
{% endif %}
{% endfor %}
</select>
</label>
</div>
<div class="form-group">
<label for="authors">作者
<select name="authors" id="authors" multiple size="3">
{% for author in authors %}
{% if author in book_obj.authors.all %}
<option value="{{ author.id }}" selected="True">{{ author.name }}</option>
{% else %}
<option value="{{ author.id }}">{{ author.name }}</option>
{% endif %}
{% endfor %}
</select>
</label>
</div>
今日作業:
1、整理博客
2、增刪編輯
3、添加分頁 http://www.cnblogs.com/yuanchenqi/articles/7652353.html#_label0
下周課程:
1 ajax
2 分頁
3 COOKKIE SESSION