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

 

转载于:https://www.cnblogs.com/Forever77/p/10165158.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值