第1章 day19
1.1 models
from django.db import models
# Create your models here.cla
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
pubDate = models.DateField()
price = models.DecimalField(max_digits=6, decimal_places=2)
read_num=models.IntegerField(default=0)
comment_num=models.IntegerField(default=0)
#书籍与出版社:一对多
publisher = models.ForeignKey(to="Publish")
# publisher = models.ForeignKey(to="Publish",related_name="Booklist") #反向查询时用Booklist 替换book_set
# 书籍与作者:多对多
authors=models.ManyToManyField("Author")
def __str__(self):
return self.title
class Publish(models.Model):
name = models.CharField(max_length=32)
addr = models.CharField(max_length=32)
tel = models.BigIntegerField()
class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
tel=models.CharField(max_length=32)
def __str__(self):
return self.name+" "+str(self.age)
class AuthorDetail(models.Model):
addr=models.CharField(max_length=32)
author=models.OneToOneField("Author")
1.2 views.py
ORM查询
#基于对象的跨表查询
# 一对多 添加数据 方式1
# publish_obj=models.Publish.objects.get(name="renmin")
# book_obj=models.Book.objects.create(title="python",price=122,pubDate="2012-12-12",publisher=publish_obj)
# 一对多 添加数据 方式2
# book_obj=models.Book.objects.create(title=title,price=price,pubDate=pubdate,publisher_id=publish_id)
# print(book_obj.title)
# obj=models.Book(title="python",price=122,pubDate="2012-12-12",publisher=publish_obj)
# obj.save()
#
################################多对多的添加###############
# book_obj=models.Book.objects.create(title=title,pubDate=pubdate,price=price,publisher_id=publish_id)
# 绑定作者关系: alex,egon
# 不能直接在第三张表中插入记录,因为没有第三张表名
# alex_id=models.Author.objects.get(name="alex").id
# egon_id=models.Author.objects.get(name="egon").id
#
# book_authors.objects.create(book_id=book_obj.id,author_id=alex_id)
# book_authors.objects.create(book_id=book_obj.id,author_id=egon_id)
#authors 字段
#绑定关系
# print(book_obj.authors.all(),"111")
# alex=models.Author.objects.get(name="alex")
# egon=models.Author.objects.get(name="egon")
# author_list=models.Author.objects.all()
# print(author_list)
# book_obj.authors.add(*author_list)
# print(book_obj.authors.all(),"3333")
#解除关系
# book_obj=models.Book.objects.get(nid=17)
# print(book_obj.authors.all())
# alex = models.Author.objects.get(name='alex')
# book_obj.authors.remove(alex)
# author_list = models.Author.objects.filter(id__gt=1)
# print(author_list)
#
# book_obj.authors.remove(*author_list)
# # 清空
# book_obj.authors.clear()
def query(request):
#################一对多查询##############
#正向查询
# # 查询 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="人民出版社")
# 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="沙河")
# print(authorDetail.author.name)
#反向查询 按表明 (小写)
#查询alex混迹在哪里
# alex=models.Author.objects.get(name="alex")
# print(alex.authordetail.addr)
####################多对多的查询################
#多对多的正向查询 按字段
#查询 python这本书所有作者的姓名跟年龄 多本书不能用get get得到的是一个对象 filter得到的是一个querset[obj1,obj2,....]
# python_obj=models.Book.objects.filter(title="python").first()
# author_list=python_obj.authors.all()
# for obj in author_list:
# print(obj.name,obj.age)
#多对多的反向查询
#alex 出版过的所有的书籍的名称
# author_alex=models.Author.objects.get(name="alex")
# book_list=author_alex.book_set.all()
# for i in book_list:
# print(i.title,i.price)
#####基于__双下划线的跨表查询
#查询 python这本书的价格
# ret=models.Book.objects.filter(title="python").values("price","title")
# print(ret)
#查询python这本书的出版社的名称和地址
#正向查询按 字段
# ret2=models.Book.objects.filter(title="python").values("publisher__name","publisher__addr")
# print(ret2)
# 反向查询 按表明 if设置了related_name: 按设置的值
# ret3=models.Publish.objects.filter(book__title="python").values("name","addr")
# print(ret3) #<QuerySet [{'name': '古人', 'addr': '北京'}]>
# 查询人民出版社出版过的所有书籍名称及价格
# ret4=models.Book.objects.filter(publisher__name="人民出版社").values("title","price")
# print(ret4)
# ret5=models.Publish.objects.filter(name="人民出版社").values("book__title","book__price")
# print(ret5)
# 查询egon出过的所有书籍的名字(多对多)
# ret6=models.Book.objects.filter(authors__name__contains="eg").values("title") #正向查询
# print(ret6)
# ret7=models.Author.objects.filter(name="egon").values("book__title") #反向查询
# print(ret7)
# 地址以山东开头的的作者出版过的所有书籍名称以及出版社名称
ret8=models.Book.objects.filter(authors__authordetail__addr__startswith="山东").values("title","publisher__name")
print(ret8)
return HttpResponse("OK")
def juheQuery(request):
from django.db.models import Avg,Count,Sum,Min,Max
# 单纯聚合函数
# 计算所有图书的平均价格
# ret=models.Book.objects.all().aggregate(priceAvg=Avg("price"))
# print(ret)
#统计每一本书的作者的个数
# ret2=models.Book.objects.all().annotate(authors_num=Count("authors"))
# # print(ret2)
# for obj in ret2:
# print(obj.title,obj.authors_num)
# 查询每一个出版社出版过的所有书籍的总价格
#方式一
# ret3=models.Book.objects.all().values("publisher__name").annotate(price_sum=Sum("price")).values("publisher__name","price_sum") #values("publisher__name")为分组条件 相当于 groupby 后面的分组条件
# print(ret3)
# 方式2
# ret4=models.Publish.objects.all().annotate(price_sum=Sum("book__price"))
# for i in ret4:
# print(i.name,i.price_sum)
# ret4 = models.Publish.objects.all().annotate(priceSum=Sum("book__price")).values("name","priceSum")
# print(ret4)
# return HttpResponse("ok")
1.3 F与Q查询
def FQquery(request):
from django.db.models import F,Q
#
ret1=models.Book.objects.filter(comment_num__gt=50)
# for n in ret1:
#
print(n.title,n.comment_num)
# ret2 =
models.Book.objects.filter(comment_num__gt=F("read_num")*2)
# print(ret2)
# for n in ret2:
#
print(n.title,n.comment_num)
#
models.Book.objects.all().update(price=F("price")+10)
# ret3 = models.Book.objects.filter(comment_num__gt=50,
read_num__gt=50
ret3 = models.Book.objects.filter(Q(comment_num__gt=100)|Q(read_num__gt=100))
print(ret3)
# 注意事项 不加Q 不能写在带有Q的前面
#
ret4=models.Book.objects.filter(price__lt=100,(Q(comment_num__gt=100)|Q(read_num__gt=100)))
# print(ret4)# 会报错
return HttpResponse("ok")
1.1 Settings加入以下可以打印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',
},
}
}