版权所有,转载请注明出处:http://guangboo.org/2013/02/01/caught-typeerror-while-rendering-not-enough-arguments-for-format-string
django在执行SQL语句时,在DEBUG模式下与非DEBUG模式下,将表现不同的结果,甚至会出现异常:“Caught TypeError while rendering: not enough arguments for format string”。
这样的现象应该是django在处理SQL语句时,对SQL中出现“%”符号的解析错误。如博客归档的SQL:
SELECT DATE_FORMAT(create_date, '%b %Y') AS yearmonth, COUNT(*) AS count,YEAR(create_date) AS year,
MONTH(create_date) AS month
FROM blog_post
GROUP BY YEAR(create_date),MONTH(create_date)
ORDER BY year DESC,month DESC
该SQL在DEBUG=False的情况下,可以正常执行,编写正常结果。但当DEBUG=True时,却会报“Caught TypeError while rendering: not enough arguments for format string”异常。在网上搜索了一下该异常,解决方法是将SQL语句中的“%”改成“%%”,即需要用“%”符号进行转义,这样就可以在DEBUG=True的情况下正常执行。但一旦将DEBUG设为False,该SQL可以正常执行,但是结果却是“%d %Y ...”,"%%"被转义成单个"%"。
因此,一个hack方法就是根据DEBUG的值使用不同的SQL:
if settings.DEBUG:
sql = """SELECT DATE_FORMAT(create_date, '%%b %%Y') AS yearmonth, COUNT(*) AS count,YEAR(create_date) AS year,MONTH(create_date) AS month
FROM blog_post GROUP BY YEAR(create_date),MONTH(create_date)
ORDER BY year DESC,month DESC"""
else:
sql = """SELECT DATE_FORMAT(create_date, '%b %Y') AS yearmonth, COUNT(*) AS count,YEAR(create_date) AS year,MONTH(create_date) AS month
FROM blog_post GROUP BY YEAR(create_date),MONTH(create_date)
ORDER BY year DESC,month DESC"""