Django中使用Q构建复杂查询

友情提醒:本文最后更新于 1853 天前,文中所描述的信息可能已发生改变,请谨慎使用。

一般我们在Django程序中查询数据库操作都是在QuerySet里进行进行,随着我们的程序越来越复杂,查询的条件也跟着复杂起来,这样简单的通过一个filter()来进行查询的条件将导致我们的查询越来越长。当我们在查询的条件中需要组合条件时(例如两个条件“且”或者“或”)时。我们可以使用Q()查询对象。

比如有以下表:

from django.db import models

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

    def __unicode__(self):
        return self.text

然后创建一些数据:

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

1. AND

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

>>> from django.db.models import Q

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

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

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

2. OR

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

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

3. NOT

使用 ~ 即可实现 NOT 查询:

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

4. Q 对象与关键字参数共用

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

# Q(...), key=value
>>> Blog.objects.filter(Q(text__contains = 'you'), text__contains = 'who')
[<Blog: who are you>]

5. OR,AND,NOT 多条件自由组合

# (A OR B) AND C AND (NOT D)
>>> Blog.objects.filter((Q(text__contains = 'you') | Q(text__contains = 'who')) & Q(text__contains = 'what') & ~Q(text__contains = 'are'))
[<Blog: what is wrong with you>]

6. 动态构建查询条件

比如定义了一个包含一些 Q 对象的列表,那么如何使用这个列表构建 AND 或 OR 查询呢? 可以使用 operator 和 reduce:

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

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

# AND
>>> Blog.objects.filter(reduce(operator.and_, q_list))
[<Blog: 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))

相关链接:
https://www.jianshu.com/p/4a758e6a8e50
https://www.cnblogs.com/huchong/p/8027962.html

上一篇:Python发布自己的包到pypi上

下一篇:Docker常用命令整理