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()

  • 相关阅读:
    js怎样生成json的数据
    JS中生成与解析JSON
    [转]js动态创建json类型
    handlebars模板库的资源
    一指流沙,倾覆了谁的年华?
    c# const与readonly 关键字的比较
    静态类和静态构造函数
    编写跨浏览器兼容的 CSS 代码的金科玉律
    mysql 分页sql
    EF报LINQ to Entities 不识别方法“Web_JZRepository.Models.copy_materials_details get_Item(Int32) ”,因此该方法无法转换为存储表达式。
  • 原文地址:https://www.cnblogs.com/Forever77/p/10165158.html
Copyright © 2011-2022 走看看