按条件顺序检索 Django 查询集
retrieving Django queryset in conditions' order
我正在尝试进行查询,以便按照我所具备的条件的顺序给我结果。
我尝试了以下方法:
if query:
word_list = query.split()
for word in word_list:
icons = icons.filter(
Q(name__iexact=word) |
Q(name__istartswith=word) |
Q(words__text__icontains=word) |
Q(name__icontains=word)
).distinct()
还有
if query:
word_list = query.split()
for word in word_list:
exact_icons = icons.filter(Q(name__iexact=word)).distinct()
start_with_icons = icons.filter(Q(name__istartswith=word)).distinct()
contains_icons = icons.filter(
Q(words__text__icontains=word) |
Q(name__icontains=word)
).distinct()
icons = exact_icons | start_with_icons | contains_icons
所以我想首先获得完全匹配的结果,然后是那些以包含该词开头且仅在结尾处包含该词的结果,但上述两种选择似乎都不起作用。
任何想法我怎样才能做到这一点?谢谢
您可以使用 chain。它执行以下操作:
list_a = ['A', 'B', 'C']
list_b = ['D', 'E', 'F']
print(list(chain(list_a, list_b)))
>>> ['A', 'B', 'C', 'D', 'E', 'F']
此处供您第二次尝试使用:
from itertools import chain
...
icons = list(chain(exact_icons, start_with_icons, contains_icons))
由于您的更新信息:
from functools import reduce, import operator
words_qs = reduce(operator.or_, (Q(name__iexact=word) for word in words))
YourModel.objects.filter(..., words_qs)
我正在尝试进行查询,以便按照我所具备的条件的顺序给我结果。 我尝试了以下方法:
if query:
word_list = query.split()
for word in word_list:
icons = icons.filter(
Q(name__iexact=word) |
Q(name__istartswith=word) |
Q(words__text__icontains=word) |
Q(name__icontains=word)
).distinct()
还有
if query:
word_list = query.split()
for word in word_list:
exact_icons = icons.filter(Q(name__iexact=word)).distinct()
start_with_icons = icons.filter(Q(name__istartswith=word)).distinct()
contains_icons = icons.filter(
Q(words__text__icontains=word) |
Q(name__icontains=word)
).distinct()
icons = exact_icons | start_with_icons | contains_icons
所以我想首先获得完全匹配的结果,然后是那些以包含该词开头且仅在结尾处包含该词的结果,但上述两种选择似乎都不起作用。 任何想法我怎样才能做到这一点?谢谢
您可以使用 chain。它执行以下操作:
list_a = ['A', 'B', 'C']
list_b = ['D', 'E', 'F']
print(list(chain(list_a, list_b)))
>>> ['A', 'B', 'C', 'D', 'E', 'F']
此处供您第二次尝试使用:
from itertools import chain
...
icons = list(chain(exact_icons, start_with_icons, contains_icons))
由于您的更新信息:
from functools import reduce, import operator
words_qs = reduce(operator.or_, (Q(name__iexact=word) for word in words))
YourModel.objects.filter(..., words_qs)