zoukankan      html  css  js  c++  java
  • 089:QuerySet API详解-count和exists

    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)

    实例代码截图:

  • 相关阅读:
    PHP获取汉字拼音首字母
    记录,待总结5
    HDU2833 WuKong Floyd
    搜索
    记录,待总结4
    HDU3350 #define is unsafe 栈的应用
    指针与引用的混合使用总结
    多源最短路径 Floyd
    引用总结
    函数返回值总结
  • 原文地址:https://www.cnblogs.com/zheng-weimin/p/10284718.html
Copyright © 2011-2022 走看看