当SQL执行时,Django原始查询不返回任何行

时间:2014-06-17 15:22:28

标签: sql django mysql-python

我正要把头撞在墙上。

考虑以下代码:

def get_cardnumbers_from_timestamp(request, since_time=0):
    if request.method == 'GET':
        if request.user:
            if not request.user.is_authenticated():
                logger.debug('User is not authorized')
                return auth_required('Authentication required')

        logger.debug('User has been authorized')
        user = request.user
        logger.debug('since_time: {0}'.format(since_time))
        if int(since_time) != 0:
            utc_time = time.mktime(time.gmtime(int(since_time)))
        else:
            utc_time = 0

        logger.debug('since_time UTC: {0}'.format(utc_time))

        devices_data = dict()
        from django.db import connection

        cursor = connection.cursor()
        query = 'SELECT c.name,c.id,d.locale,d.card_number,d.dev_uniqid,d.id FROM device_channel dc JOIN channels c on dc.channel_id = c.id JOIN devices d on dc.device_id=d.id WHERE d.card_number IS NOT NULL AND updated >= FROM_UNIXTIME({time}) ORDER BY d.id'.format(time=int(utc_time))
        logger.debug(query)
        cursor.execute(query)
        answers = cursor.fetchall()
        cursor.close()
        logger.debug(answers)

形成查询,当针对MySQL触发时,since_time显式设置为0或者未设置为全部返回约250行,Django也是如此。

但是,当我将时间戳设置为某个值时,无论哪一个,同一个形成的查询(我记录然后从日志中复制粘贴)都会在MySQL控制台中返回5行。 Django给了我一个高达0的结果集。

我可能会忽略一些非常明显的事情,但我已经尝试了很多方法,但无济于事。

任何想法都会受到欢迎。

2 个答案:

答案 0 :(得分:3)

您不应该使用字符串格式将参数传递给django原始查询,而是将它们传递给执行(同时检查docs)。例如,在你的情况下这样做:

query = """
 SELECT c.name,c.id,d.locale,d.card_number,d.dev_uniqid,d.id 
 FROM device_channel dc JOIN channels c on dc.channel_id = c.id 
 JOIN devices d on dc.device_id=d.id 
 WHERE d.card_number IS NOT NULL AND updated >= FROM_UNIXTIME(%s) 
 ORDER BY d.id
"""
cursor.execute(query, [int(utc_time)])

答案 1 :(得分:0)

默认情况下,Python DB API将返回没有字段名称的结果,这意味着您最终得到的是值列表,而不是dict。以较低的性能成本,您可以使用以下内容将结果作为dict返回:

def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]