zoukankan      html  css  js  c++  java
  • django ORM常用查询条件

    假设有一个模型

    class Article(models.Model):
        title=models.CharField(max_length=50)
        content=models.TextField()
        class Meta:
            db_table='book'

    对于查询结果是结果集,即通过filter进行查询所得的对象来说,可通过query属性来查看django转换之后的原生sql语句

    ……
    article=Article.objects.filter(title='Hello World')
        print(article.query)
        print(article)
    ……

    查询结果为

    exact:即相当于数据库底层的等号=

    article=Article.objects.filter(title__exact='Hello World'),即相当于数据库底层的select ··· from ··· where title='Hello World'

    iexact:即相当于数据库底层的like

    article=Article.objects.filter(title__iexact='Hello World'),即相当于数据库底层的select ··· from ··· where title like 'Hello World'

    contains:大小写敏感的匹配查询,也是like,注意转换后查询条件的两侧都有%

    article=Article.objects.filter(title__contains='Hello World'),即相当于数据库底层的select ··· from ··· where title like '%Hello World%'

    icontains:大小写不敏感的匹配查询

    article=Article.objects.filter(title__icontains='Hello World'),即相当于数据库底层的select ··· from ··· where title like '%Hello World%'

    in:查询条件是否在给定的范围内,用小括号和中括号都可以

    article=Article.objects.filter(id__in=(1,2,6,9)),即相当于数据库底层的select ··· from ··· where id in (1,2,6,9)

    gt:大于

    gte:大于等于

    lt:小于

    lte:小于等于

    article=Article.objects.filter(id__gt=5),即相当于数据库底层的select ··· from ··· where id > 5

    startswith:以指定某个字符串开始,大小写敏感

    istartswith:以指定某个字符串开始,大小写不敏感

    endswith:以指定某个字符串结束,大小写敏感

    iendswith:以指定某个字符串结束,大小写不敏感

    article=Article.objects.filter(title__startswith='Hello'),即相当于数据库底层的select ··· from ··· where title like 'Hello%'

    article=Article.objects.filter(title__endswith='Hello'),即相当于数据库底层的select ··· from ··· where title like %'Hello'

    range:在某个范围,即相当于between ··· and ···,用小括号和中括号都可以

    article=Article.objects.filter(id__range=(1,6)),即相当于select ··· from ··· where id between 1 and 6

    isnull:是否为空

    article=Article.objects.filter(content__isnull=False),即相当于select ··· from ··· where content is not null

    exclude:排除满足条件的

    article=Article.objects.exclude(content=False)

    order_by 按指定字段正向排序

    article=Article.objects.all().order_by('title')

    reverse:反向排序

    distinct:去重

    article=Article.objects.all().values('title').distinct()

  • 相关阅读:
    我的Win32开发抉择,Delphi老将复出
    【月入41万】Mono For Android中使用百度地图SDK
    “开源”是什么,能吃吗?
    (转)oracle中用户删除不了,ORA-01940提示 “无法删除当前已连接用户”
    Oracle 去除两边空格
    (转)C#中键值对类型Hashtable与Dictionary比较和相关用法
    (转)对Oracle导出文件错误和DMP文件结构的分析,EXP-00008: 遇到 ORACLE 错误 904 ORA-00904: "MAXSIZE": invalid identifier
    (转)ajax.dll,ajaxpro.dll的区别和用法
    npoi实现 从固定的行读取数据作为表头并返回datable
    字符串格式化测试
  • 原文地址:https://www.cnblogs.com/Forever77/p/10165158.html
Copyright © 2011-2022 走看看