django中的F和Q

F查询

Django 提供 F() 来做这样的比较。F() 的实例可以在查询中引用字段,来比较同一个 model 实例中两个不同字段的值。

查询书id大于\小于价格的书籍

1 models.Book.objects.filter(id__gt=F("price"))
2 <QuerySet []>
3 
4 models.Book.objects.filter(id__lt=F("price"))
5 <QuerySet [<Book: 书一>, <Book: 书二>, <Book: 书三>, <Book: 书四>, <Book: 书五>, <Book: 书六>]>

Django 支持 F() 对象之间以及 F() 对象和常数之间的加减乘除和取模的操作。 

1 models.Book.objects.filter(id__lt=F("price")/2)
2 <QuerySet [<Book: 书一>, <Book: 书二>, <Book: 书三>, <Book: 书四>, <Book: 书五>]>

 

修改操作也可以使用F函数,比如将每一本书的价格提高30元

models.Book.objects.all().update(price=F("price")+30)

 

字符串使用Concat连接

from django.db.models.functions import Concat
from django.db.models import Value
models.Book.objects.update(title=Concat(F("title"),Value("("),Value(""),Value(")")))

 

Q查询主要是用来做and, or, not 查询的

AND查询

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

>>> from django.db.models import Q
# Q(...)
>>> Question.objects.filter(Q(question_text__contains='you'))
[<Question: what are you doing>, <Question: what is wrong with you>, <Question: who are you>]

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

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

 

OR查询

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

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

 

NOT查询

使用 ~Q(...) 客户实现 NOT 查询:

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

 

与关键字参数共用

记得要把 Q 对象放前面:

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

 

动态构建查询条件

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

>>> lst = [Q(question_text__contains='you'), Q(question_text__contains='who')]

# OR
>>> Question.objects.filter(reduce(operator.or_, lst))
[<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_, lst))
[<Question: who are you>]

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

q = request.GET.get('q', '').strip()
lst = []
if q:
    for key in ['title__contains', 'content__contains',
                'author__name__contains']:
        q_obj = Q(**{key: q})
        lst.append(q_obj)
queryset = Entry.objects.filter(reduce(operator.or_, lst))

 

posted @ 2019-02-02 20:07  沈俊杰  阅读(873)  评论(0编辑  收藏  举报