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()
  • 相关阅读:
    如何优雅地使用 Stack Overflow
    Quartz总结
    slf4j-api、slf4j-log4j12以及log4j之间什么关系?
    eclipse 安装 spring boot suite 插件遇到的问题
    Java项目结构总结
    netstat 与 telnet
    微服务架构中的安全认证与鉴权
    git 常用命令
    session 、cookie、token的区别
    List和Set区别
  • 原文地址:https://www.cnblogs.com/lxmtx/p/13394980.html
Copyright © 2011-2022 走看看