码迷,mamicode.com
首页 > Windows程序 > 详细

089:QuerySet API详解-count和exists

时间:2019-01-17 22:44:00      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:而不是   span   分享   str   判断   tle   com   count   png   

QuerySet API详解-count和exists:

count :获取提取的数据的个数。如果想要知道总共有多少条数据,那么建议使用 count ,而不是使用 len(articles) 这种。因为 count 在底层是使用 select count(*) 来实现的,这种方式比使用 len 函数更加的高效;

 

    # book_sum = Book.objects.all()
    # print(len(book_sum))
    result = Book.objects.count()
    print(result)

first 和 last :返回 QuerySet 中的第一条和最后一条数据,如果原来数据集就是空,则返回Null;

aggregate :使用聚合函数;

exists :判断某个条件的数据是否存在。如果要判断某个条件的元素是否存在,那么建议使用 exists ,这比使用 count 或者直接判断 QuerySet 更有效得多。示例代码如下:

if Article.objects.filter(title__contains=hello).exists():
  print(True)
比使用count更高效:
if Article.objects.filter(title__contains=hello).count() > 0:
  print(True)
也比直接判断QuerySet更高效:
if Article.objects.filter(title__contains=hello):
  print(True)

实例代码截图:

技术分享图片

 

089:QuerySet API详解-count和exists

标签:而不是   span   分享   str   判断   tle   com   count   png   

原文地址:https://www.cnblogs.com/zheng-weimin/p/10284718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!