python - Django ORM orderby exact/prominent match 排在最前面

标签 python django django-queryset django-orm

我需要根据 Django ORM 中的匹配长度对结果进行排序。

我有一个 Suburb 表,在 name 字段中包含位置详细信息。

我需要用给定的文本搜索表格,并按完全匹配/最突出的匹配顺序排列在最前面

例如:

1) 如果搜索字符串是“America”,那么结果应该是 [America, South America, North America ..] 在本例中,我们找到了一个完全匹配项,它必须是第一个元素。

2) 如果搜索的是 port 那么结果应该是 ['Port Melbourne' 'Portsea', East Airport]

在这种情况下,我们发现端口在定界符之前是完全匹配的。

我知道我可以使用多个查询并将它们连接起来,例如一个用于完全匹配,另一个用于部分匹配,然后在部分匹配时使用排除连接它们就像

search_list=  [x.name for x in Suburb.objects.filter(name=search)] 
# Then
search_list += [x.name for x in Suburb.objects.filter(name__iregex=r"[[:<:]]{0}".format(search)).exclude(name__in=search_list)]

我可以这样继续下去。但是想知道我们是否有更好的方法。

有什么线索吗?

提前致谢

最佳答案

Django 2.0实现一个功能

StrIndex(string, substring)

Returns a positive integer corresponding to the 1-indexed position of the first occurrence of substring inside string, or 0 if substring is not found.

例子:

from django.db.models.functions import StrIndex

qs = (
    Suburb.objects
    .filter(name__contains='America')
    .annotate(search_index=StrIndex('name', Value('America')))
)

关于python - Django ORM orderby exact/prominent match 排在最前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46398198/

相关文章:

python - Tensorflow:如何确保每批中的所有样本都有不同的标签?

python - 如何在PyQt5中捕获libpng错误错误的自适应滤波器

python - 我想解析一个大的 csv 文件并将其上传到 mysql 数据库中,但它需要很长时间。 Python/Django

python - 如果第一个数字和长度相同,则从列表中删除数字

python - 添加列表中的数字但保留其他元素

django - 属性错误 : 'User' object has no attribute 'is_admin'

python - 尝试在 Django 1.9 中迁移——奇怪的 SQL 错误 "django.db.utils.OperationalError: near ")": syntax error"

python - 如何在查询集中使用 Django __time 查找

Django Querysets - 按相关对象中的 bool 值过滤对象

python - 用 Django 中最新的相关对象进行注释