我们正在进行站点搜索,我们在其中搜索带有 icontains
的字段。它运行良好,但出现的结果顶部没有最相关的结果。
一个例子是搜索“权力的游戏”。如果搜索“Game of”,第一个结果可能是“Crazy Game of...”,第二个结果可能是“Game of Thrones”
基本上,我想使用 icontains
进行搜索,但按 startswith
进行排序。有什么想法吗?
最佳答案
自从提出这个问题后,Django 添加了新功能,现在可以原生处理这个用例。
您可以使用 Django 的 QuerySet API 中的以下功能通过任意比较对结果进行排序:
-
Q()
Object :封装了一个可重用的查询表达式。我们的表达式将对象的字段与我们的“Game of”搜索值进行比较。 -
ExressionWrapper()
:包装一个查询表达式,以便用output_field
控制ModelField
类型。在这种情况下,类型是 bool 值。 -
annotate()
:动态添加一个ModelField
每个 QuerySet 对象,基于查询表达式的结果。我们想添加一个True
/False
字段来排序。 -
order_by()
:按指定字段对QuerySet对象进行排序。我们希望按带注释的字段值进行反向排序,以便首先显示True
值。
from django.db.model import Q, ExpressionWrapper, BooleanField
....
# Your original setup.
search_term = 'Game of'
data = MyModel.objects.filter(name__icontains=search_term)
# Encapsulate the comparison expression.
expression = Q(name__startswith=search_term)
# Wrap the expression to specify the field type.
is_match = ExpressionWrapper(expression, output_field=BooleanField())
# Annotate each object with the comparison.
data = data.annotate(my_field=is_match)
# Order by the annotated field in reverse, so `True` is first (0 < 1).
data = data.order_by('-my_field')
....
关于python - 按startwith match排序查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622501/