1. 多重过滤
1.1. 链式过滤
Entry.objects.filter(
headline__startswith='What'
).exclude(
pub_date__gte=datetime.date.today()
).filter(
pub_date__gte=datetime(2005, 1, 30)
)
filter() 和 exclude() 的结果依然是个 QuerySet,因此它可以继续被 filter() 和 exclude()(跨关系的链式过滤时注意)
1.2. 子集过滤
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())
每个子集都是独立的,不互相影响
2. Q查询
from django.db.models import Q # 引入 Q查询
2.1. 或
Q(question__startswith='Who')|Q(question__startswith='What')
相当于 WHERE question LIKE 'Who%' OR question LIKE 'What%'
2.2. 且
Poll.objects.get(
Q(question__startswith='Who'),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
相当于 SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
2.3. 关键词参数和 Q() 混合时,Q() 在前
Poll.objects.get(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),question__startswith='Who',)