Django db.connection.cursor.fetchone() returns emty result, when raw SQL doesn't
I have method in a cusom QuerySet that performs raw SQL query to database.
class QuerySet(models.query.QuerySet):
def get_short(self, language_code='en'):
"""Returns shortest name for given language"""
cursor = connection.cursor()
cursor.execute('''SELECT t.name FROM translation t, name n
WHERE n.id IN (%s)
AND t.link_id = n.id
AND t.lang_id = %s
ORDER BY CHAR_LENGTH(t.name)
LIMIT 1''', [','.join(["'%s'" % obj.pk for obj in self]), get_language(language_code).pk])
name = cursor.fetchone()
if name:
return name[0]
But it returns empty result. cursor.fetchone()
return None
instead of value. Wh开发者_Python百科en I execute raw SQL on the same database:
SELECT t.name FROM translation t, name n
WHERE n.id IN ('166','167')
AND t.link_id = n.id
AND t.lang_id = 40
ORDER BY CHAR_LENGTH(t.name)
LIMIT 1
It returns properly value.
Where I wrong? Please, help!
Try without the ", ".join
to format your first parameter.
cursor.execute('''SELECT t.name FROM translation t, name n
WHERE n.id IN %s
AND t.link_id = n.id
AND t.lang_id = %s
ORDER BY CHAR_LENGTH(t.name)
LIMIT 1''', [tuple(obj.pk for obj in self), get_language(language_code).pk])
精彩评论