原文连接:https://mozillazg.github.io/2015/11/django-the-power-of-q-objects-and-how-to-use-q-object.html
本文将讲述如何在 Django 项目中使用Q对象构建复杂的查询条件。 假设有如下的 model:
classQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')
然后我们创建了一些数据:
Question.objects.create(question_text='what are you doing',pub_date=datetime.datetime(2015,11,7))Question.objects.create(question_text='what is wrong with you',pub_date=datetime.datetime(2014,11,7))Question.objects.create(question_text='who are you',pub_date=datetime.datetime(2015,10,7))Question.objects.create(question_text='who am i',pub_date=datetime.datetime(2014,10,7))>>>Question.objects.all()[,,,]
AND 查询
将多个Q对象作为非关键参数或使用&联结即可实现AND查询:
>>>fromdjango.db.modelsimportQ# Q(...)>>>Question.objects.filter(Q(question_text__contains='you'))[,,]# Q(...), Q(...)>>>Question.objects.filter(Q(question_text__contains='you'),Q(question_text__contains='what'))[,]# Q(...) & Q(...)>>>Question.objects.filter(Q(question_text__contains='you')&Q(question_text__contains='what'))[,]
OR 查询
使用|联结两个Q对象即可实现OR查询:
# Q(...) | Q(...)>>>Question.objects.filter(Q(question_text__contains='you')|Q(question_text__contains='who'))[,,,]
NOT 查询
使用~Q(...)客户实现NOT查询:
# ~Q(...)>>>Question.objects.filter(~Q(question_text__contains='you'))[]
与关键字参数共用
记得要把Q对象放前面:
# Q(...), key=value>>>Question.objects.filter(Q(question_text__contains='you'),question_text__contains='who')[]
OR, AND, NOT 多条件查询
这几个条件可以自由组合使用:
# (A OR B) AND C AND (NOT D)>>>Question.objects.filter((Q(question_text__contains='you')|Q(question_text__contains='who'))&Q(question_text__contains='what')&~Q(question_text__contains='are'))[]
动态构建查询条件
比如你定义了一个包含一些Q对象的列表,如何使用这个列表构建AND或OR查询呢? 可以使用operator和reduce:
>>>lst=[Q(question_text__contains='you'),Q(question_text__contains='who')]# OR>>>Question.objects.filter(reduce(operator.or_,lst))[,,,]# AND>>>Question.objects.filter(reduce(operator.and_,lst))[]
这个列表也可能是根据用户的输入来构建的,比如简单的搜索功能(搜索一个文章的标题或内容或作者名称包含某个关键字):
q=request.GET.get('q','').strip()lst=[]ifq:forkeyin['title__contains','content__contains','author__name__contains']:q_obj=Q(**{key:q})lst.append(q_obj)queryset=Entry.objects.filter(reduce(operator.or_,lst))
参考资料
Parerga und Paralipomena » Blog Archive » The power of django’s Q objects
Making queries | Django documentation | Django
QuerySet API reference | Django documentation | Django
django/tests.py at master · django/django · GitHub
9.9. operator — Standard operators as functions — Python 2.7.10 documentation