首页 > 其他 > 详细

django ORM常用查询条件

时间:2018-12-23 19:03:36      阅读:152      评论:0      收藏:0      [点我收藏+]

假设有一个模型

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

 

django ORM常用查询条件

原文:https://www.cnblogs.com/Forever77/p/10165158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!