数据库如何高级快速的查询是必须掌握的技能之一,除去通常的增删改掌握高级语法可让你更加快速有效的获取你想要的数据python
from django.db import models
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
addr = models.CharField(max_length=32)
phone = models.IntegerField
def __str__(self):
return self.name
# 做者查书,设计到做者里面
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=16)
author_detail = models.OneToOneField("AuthorDetail")
# 多对多
books = models.ManyToManyField(to="Book")
def __str__(self):
return self.name
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=6)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish_day = models.DateField(auto_now_add=True)
# 书-出版社 多对一关联
publisher = models.ForeignKey(to="Publisher", to_field="id")
def __str__(self):
return self.title
class AuthorDetail(models.Model):
id = models.AutoField(primary_key=True)
city = models.CharField(max_length=32)
email = models.EmailField()
def __str__(self):
return self.city
复制代码
例如:git
queryset = Book.objects.all().aggreate(Avg("price"))
{'price__avg': 192.593333} # 查询结果(未指定键名)
models.Book.objects.all().aggregate(avg_price=Avg("price"))
{'avg_price': 192.593333} # 查询结果(指定键名)
# 若是要指定多个键值对能够增长参数
models.Book.objects.all().aggregate(Avg('price'), Min('price'), Sum('price'))
{'price__avg': 192.593333, 'price__max': Decimal('233.33'), 'price__min': Decimal('111.12'), 'price__sum': Decimal('577.78')}
复制代码
models.Book.objects.all().annotate(authorNum=Count("author"))
Output: <QuerySet [<Book: 书一>, <Book: 书二>, <Book: 书三>]>
book_list = models.Book.objects.all().annotate(authorNum=Count("author"))
for i in book_list:
print(i.authorNum)
OutPut:
2
2
1
复制代码
# 注意在反向查询字段须要双下划线
models.Publisher.all().annotate(min_price=Min("book__price"))
for i in queryset:
print(i.min_price)
Output:
111.12
12.00
456.00
785.00
# 当须要筛选其余的字段或者须要返回特定的字段值
models.Publisher.filter(name='zhan').values('phone','book__author').annotate(min_price=Min("book__price"))
for i in queryset:
print(i)
Output:
{'phone': 18895309883, 'book__author': 'zhan', 'book__price': 111.11 }
复制代码
# ps:gt在数据库筛选表示大于等于,lt小于等于
models.objects.all().annotate(au=Count("author")).filter(au__gt=1)
Output:
[queryset <book1> <book2>] # 本身看的懂就行
# 能够对上面的查询语句进行oder_by下
models.objects.all().annotate(au=Count("author")).filter(au_gt=1).oder_by(au)
复制代码
# 查询语句中name是指做者的名字,结果仍是会以键值对展现
models.Author.objects.all().annotate(total=Sum("book_price")).values("name",
"total")
复制代码
# 查询结果为querysetfile:/Users/zhanlingjie/Documents/mypython/SZKJ/eyaos_vm/server/organization/urls.py
models.Book.objects.filter(id__gt= F('price')/2)
复制代码
models.Author.objects.filter(Q(name="小一") | Q(name="小三"))
<QuerySet [<Author: 小一>, <Author: 小三>]>
Output:
1
2
3
复制代码
ORM 跨表查询
class Book(models.Model):
title = models.CharField( max_length=32)
publish=models.ForeignKey(to="Publish",to_field="id")
authors=models.ManyToManyField(to='Author',related_name='bookList') 
class Publish(models.Model):
name=models.CharField( max_length=32)
class Author(models.Model):
name=models.CharField( max_length=32)
ad=models.OneToOneField("AuthorDetail")
class AuthorDetail(models.Model):
telephone=models.BigIntegerField()
基于对象查询(sql:子查询)
一对多的关系 (Publish--Book)
正向查询,按字段:
查询python这本书的出版社所在的名称
book_obj=Book.objects.filter(title="python").first()
#print(book_obj.publish.name)
反向查询,按表名小写_set:
人民出版社出版过的全部书籍名称
publish_obj=Publish.objects.filter(name="人民出版社出版").first()
print(publish_obj.book_set.all())
for obj in publish_obj.book_set.all():
print(obj.title)
多对多的关系
正向查询,按字段:
python这本书全部做者的名字
book_obj=Book.objects.filter(title="python").first()
book_obj.authors.all()
反向查询,按表名小写_set:
alex出版过的全部书籍名称
alex=Author.objects.filter(name="alex").first()
alex.bookList.all()
一对一的关系
正向查询,按字段:
查询alex的手机号
alex=Author.objects.filter(name="alex").first()
alex.ad.telephone
反向查询:按表名小写
以151开头的手机号的做者的名字
ad=AuthorDetail.objects.get(telephone__startswith="151")
ad.author.name
基于Queryset和 __(sql:join语句):
正向查询,按字段
反向查询,按表名小写
一对多的关系 (Publish--Book)
查询python这本书的所在出版社的名称
Book.objects.filter(title="python").values("publish__name")
for obj in Book.objects.filter(title="python"):
temp={}
temp["publish__name"]=obj.publish.name
人民出版社出版过的全部书籍名称
Publish.objects.filter(name="人民出版社出版").values("book__title")
多对多的关系
python这本书全部做者的名字
Book.objects.filter(title="python").values("authors__name")
alex出版过的全部书籍名称
Author.objects.filter(name="alex").values("book__title")
一对一的关系
查询alex的手机号
Author.objects.filter(name="alex").values("ad__telephone")
以151开头的手机号的做者的名字
AuthorDetail.objects.filter(telephone__startswith="151").values("author__name")
扩展:
练习1:
查询python这本书的所在出版社的名称
Book.objects.filter(title="python").values("publish__name")
Publish.objects.filter(book__title="python").values("name")
练习2:
手机号以151开头的做者出版过的全部书籍名称以及出版社名称
Book.objects.filter(authors__ad__telephone__startswith="151").values("title","publish__name")
分组查询:
查询每个出版社出版过的书籍个数
Publish.objects.annotate(Count("book__id"))
select count(*) from publish group by id
复制代码