开发者

Django custom field - automatically add COLLATE to query

I'm trying to create a custom field which would automatically add COLLATE infor开发者_StackOverflow中文版mation into the WHERE part of SQL query:

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'

when I perform a query like this:

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

then nothing is found, even though the query (print result.query) is valid and matches several rows. Am I doing something wrong?

The reason why I'm adding the collation iformation is that I want perform queries on those fields and ignore any diacritics.


Are you using MySQL 1.2.1p2 by any chance? From the Django documentation

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜