2

MYSQL charset is UTF-8, but the data in it is GBK, and Django model reads GBK as unicode.

How can I get the right encoding?

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
fmnisme
  • 21
  • 1
  • Welcome to SO. Please read [How to ask a good question](http://stackoverflow.com/help/how-to-ask) And [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – RiggsFolly Jan 12 '16 at 13:23
  • 1
    1). You really need to mention which Python version you're using (preferably by using a tag), since Python 2 & Python 3 handle Unicode differently. 2). You _can_ do the conversion specified in your title using `u"\xb8\xa3\xbd\xa8\xd2\xbb\xc7\xf8".encode('latin1')`, but I suspect we need more info to answer your question properly. Eg, would you like your string to be converted to `u'\u798f\u5efa\u4e00\u533a'`? – PM 2Ring Jan 12 '16 at 13:38
  • 1
    My Python version is python2.7, and I use `u"\xb8\xa3\xbd\xa8\xd2\xbb\xc7\xf8".encode('latin1').decode('gbk')`, it works,thank you! – fmnisme Jan 13 '16 at 02:43
  • The sane solution is to translate your database from GBK to UTF-8 instead. – tripleee Jan 13 '16 at 05:21
  • It is a legacy database, I can not change it. – fmnisme Jan 13 '16 at 06:31
  • Can you do `SET NAMES gbk` after connecting to MySQL? That might be simpler than changing all the code. – Rick James Jan 15 '16 at 02:34
  • Is this what you are expecting? `福建一区`? – Rick James Jan 15 '16 at 02:34
  • @RickJames yes,it is,How can I `SET NAMES gbk` in django? – fmnisme Jan 18 '16 at 03:23
  • Check out http://stackoverflow.com/questions/28523138/django-character-latin1-mysql and the links there. – Rick James Jan 18 '16 at 06:48

0 Answers0