查询操作
通过Entry.objects调用查询接口
1、基本查询操作
语法:all()
用法:Entry.objects.all()
返回:QuerySet
等同于:select * from index_author
2、查询指定列
语法:values(‘列1’,‘列2’,。。。。)
用法:Entry.objects.values(‘列1’,‘列2’,。。。。)
返回:QuerySet
ex:Author.objects.values('name','age')
等同于:select name,age from index_author
注意:
values()可以用在所有的返回查询结果集的方法的后面
3、排序函数
语法:order_by('列1',‘列2’)
用法:Entry.objects.order_by('列1',‘列2’)
默认的排序规则是升序
如果需要降序,则在列前添加一个‘-’
ex:
1、Author.objects.order_by('age')
2、Author.objects.all().order_by('-age');
4、对条件取反
语法:exclude()
用法:Entry.objects.exclude()
ex:
1、Author.objects.exclude(id=3)
select * from author where not (id=3)
2、Author.objects.exclude(id=3,age=85)
select * from author where not (id=3 and age=85)
5、根据条件查询部分行数据(重难点)
方法:filter(参数)
用法:Entry.objects.filter(参数)
1、使用Entry中的属性作为查询参数
多个参数的话,使用,隔开,映射到sql语句上,是使用and来进行关联的
ex:
1、Author.objects.filter(id=1)
select * from author where id=1
2、Author.objects.filter(id=1,name='莫言')
select * from author where id=1 and name='莫言'
2、通过Fild Lookup(查询表达式)完成复杂条件的构建
查询表达式:每个查询表达式都是一个独立的查询条件,可以用在所有的有查询条件的位置处
1、__exact
作用:精确查询,等值判断
用法:Entry.objects.filter(属性__exact=值)
ex:
Author.objects.filter(id__exact=1)
select * from author where id=1
2、contains
作用:筛选出属性中包含指定关键字的记录(模糊查询)
ex:
Author.objects.filter(name__contains='ao')
select * from author where names like '%ao%'
3、__lt
作用:筛选出属性值小于指定值得记录
4、__lte
作用:筛选出属性值小于等于指定值得记录
5、__gt
作用:筛选出属性值大于指定值得记录
6、__gte
作用:筛选出属性值大于等于指定值得记录
7、__startswith
作用:筛选出以指定关键字开始的记录
8、__endswith
作用:筛选出以指定关键结尾的记录
6、查询只返回一条数据
语法:get(条件)
用法:Entry,objects.get(查询条件/表达式)
注意:该函数只适用于返回一条记录时使用