在Django/sqlite中更改text_factory [英] Change text_factory in Django/sqlite

查看:38
本文介绍了在Django/sqlite中更改text_factory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django项目,该项目使用可由外部工具写入的sqlite数据库.该文本应为UTF-8,但在某些情况下,编码中会出现错误.文本来自外部来源,因此我无法控制编码.是的,我知道我可以在外部源和数据库之间编写一个包装层",但是我宁愿不必这样做,尤其是因为数据库已经包含很多不良"数据.

I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is from an external source, so I cannot control the encoding. Yes, I know that I could write a "wrapping layer" between the external source and the database, but I prefer not having to do this, especially since the database already contains a lot of "bad" data.

sqlite中的解决方案是将text_factory更改为以下内容:lambda x:unicode(x,"utf-8","ignore")

The solution in sqlite is to change the text_factory to something like: lambda x: unicode(x, "utf-8", "ignore")

但是,我不知道该如何告诉Django模型驱动程序.

However, I don't know how to tell the Django model driver this.

我得到的例外是:

<代码>'无法将文本解码为UTF-8列'文本'在/var/lib/python-support/python2.5/django/db/backends/sqlite3/base.py执行

不知何故,我需要告诉sqlite驱动程序不要尝试将文本解码为UTF-8(至少不使用标准算法,但它需要使用我的故障安全变体).

Somehow I need to tell the sqlite driver not to try to decode the text as UTF-8 (at least not using the standard algorithm, but it needs to use my fail-safe variant).

推荐答案

sqlite中的解决方案是改变text_factory类似于:lambda x:unicode(x,"utf-8",忽略")

The solution in sqlite is to change the text_factory to something like: lambda x: unicode(x, "utf-8", "ignore")

但是,我不知道该如何告诉Django模型驱动程序.

However, I don't know how to tell the Django model driver this.

您尝试过

from django.db import connection
connection.connection.text_factory = lambda x: unicode(x, "utf-8", "ignore")

在运行任何查询之前?

这篇关于在Django/sqlite中更改text_factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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