gpt4 book ai didi

django - 如何使用 postgres 在 django 中设置对重音不敏感的过滤器?

转载 作者:行者123 更新时间:2023-11-29 11:16:50 25 4
gpt4 key购买 nike

您好,我发现在 postgres 数据库上,我们无法配置默认的重音敏感度(在旧邮件交换上)。

有没有办法让 _icontains 也对特殊字符(é、è、à、ç、ï)不敏感,或者我必须使用 postgres 正则表达式将两边替换为 _iregex (ç->c, é->e 。 ..)?

编辑:这个问题是旧的,并为 1.8 之前的 django 用户保留。对于那些使用最新 django 版本的人,这里有新的方法:https://docs.djangoproject.com/en/dev/ref/contrib/postgres/lookups/#std:fieldlookup-unaccent

最佳答案

编辑:Django 1.8 对内置的 postgresql 进行重音不敏感查找。 https://docs.djangoproject.com/en/dev/ref/contrib/postgres/lookups/#std:fieldlookup-unaccent

事实上在 postgres contrib (8.4+) 中有一个 unaccent 函数可以方便地搜索:

对于 postgres 9/8.5:

对于 postgres 8.4:

这里是 django 的用法示例:

vals = MyObject.objects.raw(
"SELECT * \
FROM myapp_myobject \
WHERE unaccent(name) LIKE \'%"+search_text+"%'")

您可以在比较前对文本搜索应用 apply unaccent。

我做的选择是:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# parts of credits comes to clarisys.fr
from django.db.backends.postgresql_psycopg2.base import *

class DatabaseOperations(DatabaseOperations):
def lookup_cast(self, lookup_type):
if lookup_type in('icontains', 'istartswith'):
return "UPPER(unaccent(%s::text))"
else:
return super(DatabaseOperations, self).lookup_cast(lookup_type)

class DatabaseWrapper(DatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
self.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
self.ops = DatabaseOperations(self)

在文件夹中使用此文件 base.py 并将此文件夹用作数据库后端。 icontains 和 istartswith 现在不区分大小写和重音。

关于django - 如何使用 postgres 在 django 中设置对重音不敏感的过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5619848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com