Bug #73867 last_executed_query returns str not unicode
Submitted: 10 Sep 2014 1:33 Modified: 6 May 2022 14:34
Reporter: Brian May Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / Python Severity:S3 (Non-critical)
Version:1.2.3 OS:Linux
Assigned to: Assigned Account CPU Architecture:Any

[10 Sep 2014 1:33] Brian May
Description:
According to https://code.djangoproject.com/ticket/18461:
last_executed_query must always return a unicode string.

However, in python-mysql-connector, using Python2 it doesn't - it returns a str containing a utf8 encoded string instead.

This causes crashes when trying to write unicode data to a database. See https://code.djangoproject.com/ticket/22377

How to repeat:
import xyz.models as m
m.Class.objects.filter(attribute=u'’')

Suggested fix:
In mysql/connector/django/base.py change:

      def last_executed_query(self, cursor, sql, params):
          return cursor.statement

To:

      def last_executed_query(self, cursor, sql, params):
          from django.utils.encoding import force_text
          return force_text(cursor.statement)

I have tested this, it works.
[23 Sep 2014 9:36] Geert Vanderkelen
Verified for Connector/Python v1.2.

Connector/Python v2.0 will try to decode the statement and return it as a unicode.

It would be indeed good to decode the statement in the Django backend for Connector/Python v1.2.

The not so elegant workaround is to decode the statement when needed.
[2 Mar 2015 23:28] Sandro Tosi
v2.0.3 didnt include this fix: can we have that in the next version please?
[4 May 2022 14:34] Nuno Mariz
Posted by developer:
 
The last_executed_query() method is now part of mysql.connector.django.operations and it's inherited by the official Django MySQL driver.