Django 的 ORM 是创建 SQL 去查询和操作数据库的一个 Python 式的方式。
注:Tb 为 模型 model 的 Class 名,比如 Post.objects.all()
1.返回 QuerySet 对象的方法
>>> Tb.objects.all()
>>> Tb.objects.filter()
>>> Tb.objects.exclude()
>>> Tb.objects.order_by()
>>> Tb.objects.reverse()
>>> Tb.objects.distinct()
2.特殊的QuerySet
>>> Tb.objects.values()
>>> Tb.objects.values_list()
续
3.返回具体对象
>>> Tb.objects.get()
>>> Tb.objects.first()
>>> Tb.objects.last()
续
4.返回布尔值的方法
>>> Tb.objects.exists()
5.返回数字的方法
>>> Tb.objects.count()
<1> Tb.objects.filter( id__lt=3, id__gt=1 )
获取 id 大于(gt) 1 且 小于(lt) 3 的值
<2> Tb.objects.filter( id__in=[2, 4, 5] )
获取 id 等于 2、4、5的数据
<3> Tb.objects.exclude( id__in=[1, 3] )
得到排除 id 等于 1、3 的数据
<4> Tb.objects.filter( title__contains="博客" )
获取 title 字段包含“博客”的数据
<5> Tb.objects.filter( title__icontains="博客" )
icontains 大小写敏感,获取 title 字段包含“博客”的数据
<6> Tb.objects.filter( id__range=[2, 5] )
获取 id 范围是 2 到 5 的数据
类似的还有:startswith、istartswith、endswith、iendswith
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有