Django自定义字段-自动添加COLLATE到查询

标签 django django-models custom-fields

我正在尝试创建一个自定义字段,它将自动将 COLLATE 信息添加到 SQL 查询的 WHERE 部分中:

class IgnoreDiacriticsField(models.TextField):

    def get_prep_lookup(self, lookup_type, value):
        if lookup_type == 'exact':
            return ' "' + self.get_prep_value(value) + '" COLLATE utf8_general_ci'

当我执行这样的查询时:

result = ModelClass.objects.filter(field='value')

那么即使查询 (print result.query) 有效并且匹配多行,也找不到任何内容。我做错了什么吗?

我添加排序规则信息的原因是我想对这些字段执行查询并忽略任何变音符号。

最佳答案

您是否使用 MySQL 1.2.1p2?来自 Django 文档

If you're using MySQLdb 1.2.1p2, Django's standard CharField class will return unicode strings even with utf8_bin collation. However, TextField fields will be returned as an array.array instance (from Python's standard array module). There isn't a lot Django can do about that, since, again, the information needed to make the necessary conversions isn't available when the data is read in from the database. This problem was fixed in MySQLdb 1.2.2, so if you want to use TextField with utf8_bin collation, upgrading to version 1.2.2 and then dealing with the bytestrings (which shouldn't be too difficult) as described above is the recommended solution.

关于Django自定义字段-自动添加COLLATE到查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3154383/

相关文章:

php - 必需的自定义 WooCommerce 结帐字段不验证输入的值

php - 查询由 post_object 自定义字段过滤的帖子

python - 从 Django 运行长时间运行的 Python 函数

python - 如何在 Django 管理站点中的“添加用户”按钮旁边添加按钮

Django,自定义管理器影响保存方法?

python - Django model.DoesNotExist 异常以某种方式替换为 AttributeError

python - 扩建/先生。开发人员随机无法从 Git pull

python - 如何使用 python-social-auth 在 Django APP 上注销 facebook 本身?

python - 列 <column> 不存在(Django 1.8)

php - WooCommerce 按到期日期和时间验证优惠券