SQLALCHEMY忽略查询的重音 [英] SQLALCHEMY ignore accents on query

查看:100
本文介绍了SQLALCHEMY忽略查询的重音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到我的用户可以将数据保存为café或 cafe,我需要能够使用不区分重音的查询来搜索这些字段。

Considering my users can save data as "café" or "cafe", I need to be able to search on that fields with an accent-insensitive query.

我找到了 https://github.com/djcoin/django-unaccent/ ,但是我不知道是否有可能在sqlalchemy上实现类似的功能。

I've found https://github.com/djcoin/django-unaccent/, but I have no idea if it is possible to implement something similar on sqlalchemy.

我正在使用PostgreSQL,因此,如果解决方案专用于该数据库对我来说是好方法。如果是通用解决方案,那就更好了。

I'm using PostgreSQL, so if the solution is specific to this database is good to me. If it is generic solution, it is much much better.

感谢您的帮助。

推荐答案

首先在PostgreSQL中安装unaccess扩展:创建扩展unaccent;

First install the unaccess extension in PostgreSQL: create extension unaccent;

接下来,声明Python中的SQL函数 unaccent

Next, declare the SQL function unaccent in Python:

from sqlalchemy.sql.functions import ReturnTypeFromArgs

class unaccent(ReturnTypeFromArgs):
    pass

并像这样使用它:

for place in session.query(Place).filter(unaccent(Place.name) == "cafe").all():
    print place.name

请确保您拥有如果表很大,则使用正确的索引,否则将导致全表扫描。

Make sure you have the correct indexes if you have a large table, otherwise this will result in a full table scan.

这篇关于SQLALCHEMY忽略查询的重音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆