我需要根据 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/