Django ORM 查询补充

数据库如何高级快速的查询是必须掌握的技能之一,除去通常的增删改掌握高级语法可让你更加快速有效的获取你想要的数据python


model(准备测试模型):

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
复制代码

1.聚合查询

  • aggregate()是查询的终止子句,查询结果是返回一个键值对的字典数据,生成的键名能够自动生成,也能够人为指定

例如: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')} 

复制代码

2.分组查询

  • 为调用的QuerySet中每个对象都生成一个独立的统计值

2.1 统计每一本书的做者个数

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
复制代码

2.2 统计每一个出版社卖的最便宜的书

# 注意在反向查询字段须要双下划线
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 }

	
复制代码

2.3 统计不仅有一个做者的图书

# 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)
复制代码

2.4 查询做者出的书的总价格

# 查询语句中name是指做者的名字,结果仍是会以键值对展现
models.Author.objects.all().annotate(total=Sum("book_price")).values("name", 
"total")
复制代码

3. F查询

  • 上述的聚合查询,分组查询都是让数据库中的数据与限制的常量比较,可是若是在同一张表或者关联表之间的字段比较或者加入字段的加、减、乘、除的运算,上述几种方法实现有难度,因此要引用F查询。

3.1书本中的价格须要与书本的id进行比较(实际不存在这种场景)

# 查询结果为querysetfile:/Users/zhanlingjie/Documents/mypython/SZKJ/eyaos_vm/server/organization/urls.py
models.Book.objects.filter(id__gt= F('price')/2)

复制代码

4. Q查询

  • 当须要对同一个字段有不一样的条件进行筛选时,多者属于or关系

4.1 查询做者的名字(小三或者 小一)

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')&emsp;

    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
复制代码
相关文章
相关标签/搜索