在Django中使用Q()动态构建复杂的查询 [英] Dynamically build complex queries with Q() in Django
本文介绍了在Django中使用Q()动态构建复杂的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
# ANDing Q objects
q_object = Q()
q_object.add(Q(), Q.AND)
# ORing Q objects
q_object = Q()
q_object.add(Q(), Q.OR)
>>> import operator
# create a list of Q objects
>>> mylist = [Q(question__contains='dinner'), Q(question__contains='meal')]
# OR
>>> Poll.objects.filter(reduce(operator.or_, mylist))
[<Poll: what shall I make for dinner>, <Poll: what is your favourite meal?>]
# AND
>>> Poll.objects.filter(reduce(operator.and_, mylist))
[]
例如,对于在eBay上使用条件过滤器构建页面查询时,此技术可能非常有用.
This technique might be very useful, for building queries for pages with conditional-filters for example, like on eBay.
但是,据我所知-尚未记录,因此存在针对此问题的最佳实践,这些最佳实践不会从支持中删除,也不会使阅读我的代码的人感到困惑?
But this things, as I know - not documented, so what best practices are exist for this matter, which will not be dropped from support, and will not confuse people who will read my code?
ps
而且-使用&"是否是一个好的解决方案Q()对象的运算符?在Django文档中,我什么都没找到!
ps
And also - is it good solution to use "&" operator with Q() objects? In Django-docs I found nothing about it!
推荐答案
Check the doc
It's fine to use &
or operator.and_
to represent 'AND'
, or shorter:
>>> mylist = [Q(question__contains='dinner'), Q(question__contains='meal')]
# AND
>>> Poll.objects.filter(reduce(operator.and_, mylist))
# could be
>>> Poll.objects.filter(*mylist)
这篇关于在Django中使用Q()动态构建复杂的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文