Django 搜索查询以匹配 PostgreSQL 中带或不带重音的名称

问题描述 投票:0回答:1

我正在使用 Django 和 PostgreSQL 数据库。在我的数据库中,我有一个包含名称列的用户表,该列存储带有特殊字符的名称,例如重音符号和字母“Ñ”。执行搜索时,我希望结果包含带重音符号和不带重音符号的条目。例如,如果我有名为“lúlú”和“lulu”的用户,我希望两者都出现在搜索结果中,无论搜索词是否包含重音符号。

这是我当前的搜索功能代码:

def autocomplete(request):
result = []
try:
    if request.user.is_staff and request.user.is_active:
        columns = request.GET.get("column_name").split(",")
        value = request.GET.get("column_value")
        columns = [
            ("{}__icontains".format(column), request.GET.get("term"))
            for column in columns
        ]
        filters = request.GET.get("filters", [])
        if filters:
            filters = filters.split(",")
            filters = [tuple(x.split("=")) for x in filters]
        queryset = Filter(
            app_label=request.GET.get("app_label"),
            model_name=request.GET.get("model"),
        ).filter_by_list(columns, operator.or_, filters)
        for q in queryset:
            result.append(
                {"obj": q.to_json(), "label": str(q), "value": q.to_json()[value]}
            )
except AttributeError:
    pass
return HttpResponse(json.dumps(result, cls=Codec), content_type="application/json")

如何修改我的搜索以忽略重音符号和特殊字符,以便搜索“lulu”也匹配“lúlú”,反之亦然?对于使用 PostgreSQL 在 Django 中处理不区分重音的搜索有什么建议吗?

python django postgresql search unicode
1个回答
0
投票

我相信您必须自己编写一个辅助函数,这里有一个脚本可以为您提供指导:

words = [
    "Águeda",
    "Ålborg",
    "León",
    "Cancún",
    "Coimbra",
    "São Paulo",
    "Jönköping",
    "München",
    "Nykøbing Mors",
]

char_map = {
    "a": ["ã"],
    "A": ["Å", "Á"],
    "o": ["ó", "ö", "ø"],
    "u": ["ü", "ú"]
}


def find_chr(value):
    """
    Function to find a correspondent character
    in the map dict
    """
    for key, chr_list in char_map.items():
        if value in chr_list:
            return key

    return value


def mutate(value):
    """
    Function that find if a word has a
    mutation. To increase performance
    the verification is narrowed down to
    latin alphabet.
    """
    word = ""

    for chr in value:
        code_point = ord(chr)
        if (
            code_point >= ord("a")
            and code_point <= ord("z")
            or code_point >= ord("a")
            and code_point <= ord("z")
        ):
            word += chr
        else:
            word += find_chr(chr)

    has_mutation = False if value == word else True

    return word, has_mutation


for w in words:
    search_array = [w]

    [mutation, has_mutation] = mutate(w)
    if has_mutation:
        search_array.append(mutation)

    print(search_array)

结果是将在

search
查找中得到的
__in
数组。

© www.soinside.com 2019 - 2024. All rights reserved.