1.单查询
查询书名中含有Python的书籍
results=Book.objects.filter(title__contains='Python')
<=>select * from book where title like '%Python%';
其他的可选控制字符:__gt,__lt,__gte,
2.组合查询
results=Book.objects.filter(title='Python',author='Jack chen')
<=> select * from book where title='Python' and author='Jack chen';
3.QuerySet很像一个列表
它实现部分列表实现的功能(迭代、索引、切换、获取长度等),如果QuerySet不能完成你的操作,你可以使用list函数将其转换为一个列表,但不建议这么做,因为QuerySet里面包含很多对象的话,会给数据库和系统内存造成巨大负担。
4.QuerySet是懒惰的
只有在必要的时候才会去执行数据库查询,比如下面的例子:
a=A.objects.filter(last_name='lun')
b=a.objects.filter(middle_name='jie')
c=b.objects.filter(first_name='zhou')
<=>A.object.filter(last_name='lun').filter(middle_name='jie').filter(first_name='zhou')
5.查询结果排序:
a=Book.objects.all().order_by('title')
a=Book.objects.all().order_by('title')[:5]
a=Book.objects.all().order_by('title','author') #先按照title排,相同的title按照author排
a=Book.objects.all().order_by('-title') #减号,倒叙排序
a=Book.objects.all().reverse() #QeurySet倒叙排序.
6.其他有用方法:
distinct()
values()
>>>Person.objects.values('first') #返回字典
[{'first':u'John'},{'first':u'Jane'}]
values_list()
>>>Person.objects.value_list('last') #返回tuple
[(u'Doe',),(u'Doe')]
7.Q查询
QuerySet可以通过一个Q的关键字参数封装类进一步参数化,它允许你使用更复杂的逻辑,如& 和 | 来组成 AND 和 OR关系,其结果是他可以作为filter或者exclude方法的关键字参数,例如:
>>>from django.db.models import Q
specific_does=Person.objects.filter(last='Doe').exclude(Q(filter='John')|Q(moddle='Quety'))
#example
first_name=['John','Jane','Jeremy','Julia']
first_name_keywords=Q() #empty 'query' to build on
for name in first_name:
first_name_keywords=first_name_keywords|Q(first=name)
specific_does=Person.object.filter(last='Doe').filter(first_name_keyworkds)
8.自定义sql语句
你可以到底层的数据库结构上执行自定义sql语句,django的ORM也是使用这些模块和数据库交互的。根据django数据库设置不同,这些模块也会随之变化,通常他们都符合django db-api标准,只需要导入django.db.connection对象,就可以获取数据库游标进行查询了。
from django.db import connection
cursor=connection.cursor()
cursor.execute("select * from book where name ='my lift'")
res_row=cursor.fetchall()
for row in res_row:
print('%s %s' % (row[0],row[1]))