zoukankan      html  css  js  c++  java
  • Diango中的查询集和过滤集

    一、查询集和过滤集

    all()  返回所有的数据

    filter()  返回符合条件的数据

    exclude()  过滤掉符合条件的数据

    order_by()  排序

    values()  一条数据就是一个字典,返回一个列表

    get()  返回一个满足条件的对象;如果没有找到符合条件的对象,会引发模型类.DoesNotExist异常;如果找到多个,会引发模型类.MultiObjectsReturned异常

    first()  返回查询集中的第一个对象

    last()  返回查询集中的最后一个对象

    count()  返回当前查询集中的对象个数

    exists()  判断查询集中是否有数据,如果有数据返回true,如果没有返回false

    注意:

      first和last默认情况下可以正常从QuerySet中获取,但是存在隐藏的bug,即可能会出现first和last获取到的是相同的对象,解决方案是手动写排序规则,即先排序再获取。

    二、实例

    1、all

    persons = Person.objects.all()

    2、filter/exclude

    person20 = persons.filter(p_age=20)
    person50 = persons.exclude(p_age__lt=40).filter(p_age__lt=50)
    person30 = persons.exclude(p_age__lt=30).filter(p_age__lt=40).filter(p_sex=1)
    person55 = persons.filter(p_age__in=[50,55,57])

    3、order_by

    persons = Person.objects.all().order_by('-p_age')

    4、values

    person_list = Person.objects.all().values()

    5、get

    person_exists = Person.objects.get(p_age=1)

    6、first

    person_get = Person.objects.all().first()

    7、last

    person_last = Person.objects.all().last()

    8、count

    person_count = Person.objects.all().count()

    9、exists

    person_exists = Person.objects.all().exists()
  • 相关阅读:
    API响应
    利用postman 实现Get和Post测试
    Postman 使用详解
    斐讯K2 22.5.9固件刷华硕固件实测教程
    Python多线程
    Ubuntu 16.04 上安装 MySQL 5.7 教程
    python 实战爬虫项目,学会这个32个项目天下无敌
    目录
    zip 下载解压
    滑动
  • 原文地址:https://www.cnblogs.com/lxmtx/p/13394980.html
Copyright © 2011-2022 走看看