Search code examples
mysqldjangounicodedjango-viewsmysql-error-1064

Encoding a field result coming from a query


In Django, I´m using an external command for throw a query against MySQL. All is getting great until I recover a field with utf-8 characters (kind of Camión). In that point I can´t go through to the queryset anymore and MySQL returns

'ascii' codec can't encode character u'\xf3' in position 34: ordinal not in range(128)

My code is the next one:

cursor = connection.cursor()
query = "SELECT * FROM " + table_name + " ORDER BY " + "1"
cursor.execute(query)

rows = cursor.fetchall()
for row in rows:
    result = []
    for field in row:
        print field
        result += [str(field)]

How can I avoid this situation? Thanks Mates...

EDITED: It works through field = unicode(field).encode("utf-8", "replace")


Solution

  • Try adding the below line at the beginning of your python script

    # -*- coding: utf-8 -*-