单表查询

Django测试环境的搭建

想要使用app文件夹里面的test文件,就一定要在他里面先配置好,才行。

 	 import os
     if __name__ == "__main__":
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "one_search.settings") #这里的one_search要改成你自己的Django项目名字。
        import django
        django.setup()
        # 你就可以在下面测试django任何的py文件

单表查询

增删改我们都已经知道了,所以只写上查询。

查询的必知必会的13条

  1. all ( ) 查询所有

    res = models.Book.objects.all()  # 惰性查询 数据类型:QuerySet
    
  2. filter ( ) 根据条件查询

    res = models.Book.objects.filter(pk=2) #数据类型:QuerySet
    
  3. get ( ) 不推荐使用,因为只要找不到数据就直接报错了。查询到的数据是数据对象本身

  4. first ( ) 拿第一个

    res = models.Book.objects.first() #数据类型:数据对象本身
    
  5. last ( ) 拿最后一个

    res = models.Book.objects.last() #数据类型:数据对象本身
    
  6. exclude ( ) 除此之外

    res = models.Book.objects.exclude(pk=3).filter(pk=4).filter(pk=1)
    # 结果是除此之外的所有数据,后面还可以跟查询。数据类型:QuerySet
    
  7. values( ) 列表套字典

    res = models.Book.objects.values('title') #数据类型:QuerySet
    
  8. values_list ( ) 列表套元组

    res = models.Book.objects.values_list('title') #数据类型:QuerySet
    
  9. count ( ) 统计数据的个数

    res = models.Book.objects.values_list('title') 
    
  10. distinct ( ) 去重:数据必须是一模一样的情况下,包括主键。

    res = models.Book.objects.all().distinct() # 所以在本案例中,这条语句搜索出来的结果还是原结果。
    res1 = models.Book.objects.values('title','price').distinct() #这条语句是只查询出了两个字段,所以只要这两个字段完全一样就可以去重。
    
  11. order_by ( ) 排序:默认是升序,价格负号就是降序

    res = models.Book.objects.order_by('price')
    res1 = models.Book.objects.order_by('-price')
    #可以在后面再加 order_by,当相同的时候,按照什么来排序。
    
  12. reverse ( ) 前面必须是排序结果才能反转,否则不作处理,但是不会报错。

    res = models.Book.objects.order_by('price').reverse()
    
  13. exists ( ) 没有卵用的东西

    res = models.Book.objects.filter(pk=1).exists() #判断是否存在,返回true或者false。。。。。
    

神奇的双下划线查询

    查询价格大于200的书籍
    res = models.Book.objects.filter(price__gt=200)
    查询价格小于200的书籍
    res = models.Book.objects.filter(price__lt=200)
    print(res)
    查询价格大于或者等于200的书籍
    res = models.Book.objects.filter(price__gte=200)
    查询价格小于或者等于200的书籍
    res1 = models.Book.objects.filter(price__lte=200)
    print(res,res1)

    价格是200 或者是123.23 或者666.66
    res = models.Book.objects.filter(price__in=[200,123.23,666.66])
    print(res)
    价格在200 到700之间的书籍
    res = models.Book.objects.filter(price__range=(200,666.66))  # 顾头不顾尾
    print(res)
查询书籍名称中包含p的
    res = models.Book.objects.filter(title__contains='p')  # 区分大小写
    print(res)
    忽略大小写
    res = models.Book.objects.filter(title__icontains='p')  # 忽略大小写
    print(res)


    查询书籍名称是以三开头的书籍
    res = models.Book.objects.filter(title__startswith='三')
    查询书籍名称是以p结束的书籍
    res1 = models.Book.objects.filter(title__endswith='P')
    print(res1)


    查询出版日期是2019年的书籍
    res = models.Book.objects.filter(publish_date__year='2019')
    查询出版日期是10月的书籍
    res = models.Book.objects.filter(publish_date__month='10')

posted @ 2019-10-27 16:52  chanyuli  阅读(137)  评论(0编辑  收藏  举报