1. 多重过滤

1.1. 链式过滤

  1. Entry.objects.filter(
  2. headline__startswith='What'
  3. ).exclude(
  4. pub_date__gte=datetime.date.today()
  5. ).filter(
  6. pub_date__gte=datetime(2005, 1, 30)
  7. )

filter() 和 exclude() 的结果依然是个 QuerySet,因此它可以继续被 filter() 和 exclude()(跨关系的链式过滤时注意)

1.2. 子集过滤

  1. >>> q1 = Entry.objects.filter(headline__startswith="What")
  2. >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
  3. >>> q3 = q1.filter(pub_date__gte=datetime.date.today())

每个子集都是独立的,不互相影响

2. Q查询

  1. from django.db.models import Q # 引入 Q查询

2.1. 或

  1. Q(question__startswith='Who')|Q(question__startswith='What')

相当于 WHERE question LIKE 'Who%' OR question LIKE 'What%'

2.2. 且

  1. Poll.objects.get(
  2. Q(question__startswith='Who'),
  3. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  4. )

相当于 SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')

2.3. 关键词参数和 Q() 混合时,Q() 在前

  1. Poll.objects.get(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),question__startswith='Who',)