Django模型utf8与遗留数据库 [英] Django model utf8 with legacy database

查看:121
本文介绍了Django模型utf8与遗留数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有latin1编码的遗留数据库。我没有权限将其更改为utf8。当我从模型中读取值时,我会发生乱码。



我试图使用name.decode('utf-8'),但是它抛出了一个unicode错误:

 'ascii'编解码器无法编码位置4-12中的字符:序号不在范围(128)

name.encode('utf-8')也不工作。

解决方案

如果您可以访问settings.py文件,那么可以更改数据库使用的设置'latin1'。



以下是settings.py文件中DATABASES配置的示例。

  DATABASES = {
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME' test_db',
'USER':'root',
'PASSWORD':'',
'HOST':'',
'PORT':'3306',
'OPTIONS':{
'charset':'latin1',
'use_unicode':True,},
},
}

我之前有类似的问题,请在这里查看链接 Django数据库字符集问题


I have a legacy database with latin1 encoding. I do not have access to change it to utf8. When I read values from the model, I am getting garbled text.

I tried to use name.decode('utf-8') but it is throwing a unicode error:

 'ascii' codec can't encode characters in position 4-12: ordinal not in range(128)

name.encode('utf-8') doesnt work either.

解决方案

If you have access to your 'settings.py' file, then you can change the settings saying that your database is using 'latin1'.

Following is the example of the 'DATABASES' configuration in 'settings.py' file.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_db',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '3306',
        'OPTIONS': {
                    'charset': 'latin1',
                    'use_unicode': True, },
    }, 
}

I had similar issue earlier, checkout the link here Django database charset issue

这篇关于Django模型utf8与遗留数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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