原文連接: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