使用 Django Q 对象构建复杂的查询

from django.db import models

class Question(models.Model):
    text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('published_date')

    def __unicode__(self):
        return self.text

先在 settings.py 中进行设置:

TIME_ZONE = 'Asia/Shanghai'

LANGUAGE_CODE = 'zh-CN'

然后创建一些数据:

>>> Question.objects.create(
    text='what are you doing',
    pub_date=datetime.datetime(2015, 11, 7)
)
>>> Question.objects.create(
    text='what is wrong with you',
    pub_date=datetime.datetime(2014, 11, 7)
)
>>> Question.objects.create(
    text='who are you',
    pub_date=datetime.datetime(2015, 10, 7)
)
>>> Question.objects.create(
    text='who am i',
    pub_date=datetime.datetime(2014, 10, 7)
)
>>> Question.objects.all()
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>, <Question: who am i>]
AND

将多个 Q 对象作为非关键字参数或使用 & 联结即可实现 AND 查询:

>>> from django.db.models import Q

# Q(...)
>>> Question.objects.filter(Q(text__contains = 'you'))
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>]

# Q(...), Q(...)
>>> Question.objects.filter(Q(text__contains = 'you'), Q(text__contains = 'what'))
[<Question: what are you doing>, <Question: what is wrong with you>]

# Q(...) & Q(...)
>>> Question.objects.filter(Q(text__contains = 'you') & Q(text__contains = 'what'))
[<Question: what are you doing>, <Question: what is wrong with you>]
OR

使用 | 联结两个 Q 对象即可实现 OR 查询:

# Q(...) | Q(...)
>>> Question.objects.filter(Q(text__contains = 'you') | Q(text__contains = 'who'))
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>, <Question: who am i>]
NOT

使用 ~ 即可实现 NOT 查询:

# ~Q(...)
>>> Question.objects.filter(~Q(text__contains = 'you'))
[<Question: who am i>]

扩展:
想按条件过滤掉某些数据,如何表示“不等于”这个概念呢?

>>> Question.objects.filter(text != '')

上面这种写法是错误的,正确的写法是:

# exclude
>>> Question.objects.exclude(text = '')
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>, <Question: who am i>]

# ~Q(...)
>>> Question.objects.filter(~Q(text = ''))
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>, <Question: who am i>]
Q 对象与关键字参数共用

Q 对象可以结合关键字参数一起传递给查询函数,不过需要注意的是要将Q 对象放在关键字参数的前面:

# Q(...), key=value
>>> Question.objects.filter(Q(text__contains = 'you'), text__contains = 'who')
[<Question: who are you>]
OR,AND,NOT 多条件自由组合
# (A OR B) AND C AND (NOT D)
>>> Question.objects.filter((Q(text__contains = 'you') | Q(text__contains = 'who')) & Q(text__contains = 'what') & ~Q(text__contains = 'are'))
[<Question: what is wrong with you>]
动态构建查询条件

比如定义了一个包含一些 Q 对象的列表,那么如何使用这个列表构建 ANDOR 查询呢? 可以使用 operatorreduce

>>> import operator
>>> q_list = [Q(text__contains = 'you'), Q(text__contains = 'who')]

# OR
>>> Question.objects.filter(reduce(operator.or_, q_list))
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>, <Question: who am i>]

# AND
>>> Question.objects.filter(reduce(operator.and_, q_list))
[<Question: who are you>]

这个列表也可能是根据用户的输入来构建的,比如简单的搜索功能(搜索一个文章的标题或内容或作者包含某个关键字):

q = request.GET.get('q', '').strip()
q_list = []
if q:
    for key in ['title__contains', 'content__contains', 'author__contains']:
        q_list.append(Q(**{key: q}))
    queryset = Entry.objects.filter(reduce(operator.or_, q_list))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容