一、Complex lookups with Q objects(Q对象的复杂查询)
仅仅靠单一的关键字参数查询已经很难满足查询要求。此时Django为我们提供了Q查询:
class Q
1、Q对象(django.db.models.Q)可以对关键字参数进行封装,从而更好地应用多个查询,下面是最简单的例子:
from django.db.models import Q from login.models import New #假设在我的login app的models.py下有New数据类 q1=New.objects.filter(Q(question__startswith='What'))
2、可以组合使用&,|操作符,当一个操作符是用于两个Q的对象,它产生一个新的Q对象。
Q(question__startswith='Who') | Q(question__startswith='What')
3、Q对象可以用~操作符放在前面表示否定,也可允许否定与不否定形式的组合
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
4、应用范围:
Each lookup function that takes keyword-arguments (e.g. filter(), exclude(), get()) can also be passed one or more Q objects as positional (not-named) arguments. If you provide multiple Qobject arguments to a lookup function, the arguments will be “AND”ed together. For example:
Poll.objects.get( Q(question__startswith='Who'), Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) )
... roughly translates into the SQL: SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
5、Q对象可以与关键字参数查询一起使用,不过一定要把Q对象放在关键字参数查询的前面。
正确: Poll.objects.get( Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)), question__startswith='Who')
错误: Poll.objects.get( question__startswith='Who', Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
参考官网:https://docs.djangoproject.com/en/1.5/topics/db/queries/#django.db.models.Q
转载地址:http://www.360doc.com/content/14/0425/09/16044571_372021643.shtml