Django ORM orderby exact/prominent match 排在最前面
Django ORM orderby exact / prominent match to be on top
我需要根据 Django ORM 中的匹配长度对结果进行排序。
我有一个 Suburb
table,在 name
字段中包含位置详细信息。
我需要用给定的文本搜索 table 并按完全匹配/最突出的匹配顺序排列为顶部
例如:
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)]
我可以这样下去。但是想知道我们有没有更好的方法。
有线索吗?
提前致谢
基于func
postgres 的解决方案(并且应该在 mysql 中工作,但不是测试):
from django.db.models import Func
class Position(Func):
function = 'POSITION'
arg_joiner = ' IN '
def __init__(self, expression, substring):
super(Position, self).__init__(substring, expression)
Suburb.objects.filter(
name__icontains=search).annotate(
pos=Position('name', search)).order_by('pos')
编辑: 根据 Tim Graham 的修复,在 Django docs - Avoiding SQL injection 中推荐。
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')))
)
我需要根据 Django ORM 中的匹配长度对结果进行排序。
我有一个 Suburb
table,在 name
字段中包含位置详细信息。
我需要用给定的文本搜索 table 并按完全匹配/最突出的匹配顺序排列为顶部
例如:
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)]
我可以这样下去。但是想知道我们有没有更好的方法。
有线索吗?
提前致谢
基于func
postgres 的解决方案(并且应该在 mysql 中工作,但不是测试):
from django.db.models import Func
class Position(Func):
function = 'POSITION'
arg_joiner = ' IN '
def __init__(self, expression, substring):
super(Position, self).__init__(substring, expression)
Suburb.objects.filter(
name__icontains=search).annotate(
pos=Position('name', search)).order_by('pos')
编辑: 根据 Tim Graham 的修复,在 Django docs - Avoiding SQL injection 中推荐。
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')))
)