Python错误:字符串格式化时未转换所有参数

0 投票
1 回答
1769 浏览
提问于 2025-04-18 16:11

我正在运行以下代码段来打印一个 jasper 报告,在 OpenERP 中。

prev_open_fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft'), ('date_start', '<', fiscal_date_start)]) # prev_open_fiscalyear_ids gets a list of numbers from this code
cr.execute("SELECT id \
                        FROM account_period \
                        WHERE fiscalyear_id IN %s" , (tuple(prev_open_fiscalyear_ids)))
prev_period_ids = filter(None, map(lambda x:x[0], cr.fetchall()))

这里的 cr 是指向 PostgreSQL 数据库的游标,但我遇到了以下错误:

客户端报告错误

服务器日志显示:

[2014-08-06 10:27:47,625][ASCO_ERP] ERROR:web-services:[01]: Exception: not all arguments converted during string formatting
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[02]: Traceback (most recent call last):
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[03]:   File "/home/zbeanz/workspace/KIAK/service/web_services.py", line 724, in go
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[04]:     (result, format) = obj.create(cr, uid, ids, datas, context)
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[05]:   File "/home/zbeanz/workspace/KIAK/addons/jasper_reports/jasper_report.py", line 287, in create
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[06]:     data['records'] = d.get( 'records', [] )
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[07]:   File "/home/zbeanz/workspace/KIAK/addons/kiak_tb_report/JasperDataParser.py", line 53, in get
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[08]:     self.generate_records(self.cr, self.uid, self.ids, self.data, self.context) or default_value
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[09]:   File "/home/zbeanz/workspace/KIAK/addons/kiak_tb_report/report/trial_balance_report.py", line 149, in generate_records
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[10]:     WHERE fiscalyear_id IN %s" % (tuple(prev_open_fiscalyear_ids)))
[2014-08-06 10:27:47,626][ASCO_ERP] ERROR:web-services:[11]: TypeError: not all arguments converted during string formatting

这个查询有什么问题呢?

1 个回答

2

目前,tuple(prev_open_fiscalyear_ids) 被当作一系列参数来替换查询中的内容。但这并不是你想要的,你希望你的元组能作为一个单独的参数来使用:

cr.execute(query, (tuple(prev_open_fiscalyear_ids),))

如果我没有理解错的话,这样做也应该可以:

cr.execute(query, (prev_open_fiscalyear_ids,))

最后的逗号是因为 (x)x 是一样的,而 (x,) 是一个只有一个元素的元组。

撰写回答