当原始SQL没有时,Django db.connection.cursor.fetchone()返回emty结果

时间:2011-09-14 10:44:26

标签: python sql django mysql-python

我在一个cusom QuerySet中有方法,它对数据库执行原始SQL查询。

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]

但它返回空结果。 cursor.fetchone()返回None而不是值。当我在同一个数据库上执行原始SQL时:

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

它返回正确的值。

哪里错了?请帮助!

1 个答案:

答案 0 :(得分:3)

尝试不使用", ".join格式化您的第一个参数。

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])