python - 按startwith match排序查询结果

标签 python django django-queryset

我们正在进行站点搜索,我们在其中搜索带有 icontains 的字段。它运行良好,但出现的结果顶部没有最相关的结果。

一个例子是搜索“权力的游戏”。如果搜索“Game of”,第一个结果可能是“Crazy Game of...”,第二个结果可能是“Game of Thrones”

基本上,我想使用 icontains 进行搜索,但按 startswith 进行排序。有什么想法吗?

最佳答案

自从提出这个问题后,Django 添加了新功能,现在可以原生处理这个用例。

您可以使用 Django 的 QuerySet API 中的以下功能通过任意比较对结果进行排序:

  1. Q() Object :封装了一个可重用的查询表达式。我们的表达式将对象的字段与我们的“Game of”搜索值进行比较。
  2. ExressionWrapper() :包装一个查询表达式,以便用output_field 控制ModelField 类型。在这种情况下,类型是 bool 值。
  3. annotate() :动态添加一个ModelField每个 QuerySet 对象,基于查询表达式的结果。我们想添加一个 True/False 字段来排序。
  4. 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/

相关文章:

python - 如何在 Sanic 中使用 aiohttp ClientSession?

python - Amazon Linux 实例使用 subprocess.run 在 Python 脚本中死机

python - Django:在验证之前处理表单字段

python - 使用 appengine/python 时,zipimported 模块导入会在内存中缓存多长时间?有没有办法将它们保留在内存中?

django - 如何在反向关系中使用自定义管理器?

python - Django:正确请求数据库以计算 DAU

python - Django:注释每个对象的重复值个数的计数

python /OpenCV : Converting images taken from capture

python - Django 1.8.8 迁移首先什么也没说,然后不会应用更改

sql - 带有 "isnull"参数的 Django 查询集返回重复项