我有这个原始查询:
counters = Counter.objects.raw("""
SELECT id, name FROM building_counter c
INNER JOIN scope_scope_buildings ssb
ON c.building_id = ssb.building_id
AND ssb.scope_id = %s
WHERE energy_id = %s
AND parent_id is not NULL
AND type = "C"
""", [self.id, energy_id])
结果给了我:
TypeError: not enough arguments for format string
[2, 1L]
我不明白它有什么问题:s
答案 0 :(得分:2)
真正的问题是你将列表传递给params,但是你试图在结果上调用 repr (我只知道这一点,因为我在运行时遇到了同样的问题它在ipython)。你需要做的是传入一个元组:
counters = Counter.objects.raw("""
SELECT id, name FROM building_counter c
INNER JOIN scope_scope_buildings ssb
ON c.building_id = ssb.building_id
AND ssb.scope_id = %s
WHERE energy_id = %s
AND parent_id is not NULL
AND type = 'C'
""", (self.id, energy_id))
或者您可以将this patch应用于您的django源,当您进入shell时,它会将这些转换为元组。
如果你不经常使用shell进行原始查询,你可以忽略它,因为django的其余部分处理list params就好了。
答案 1 :(得分:1)
您必须使用'%s'
代替%s
counters = Counter.objects.raw("""
SELECT id, name FROM building_counter c
INNER JOIN scope_scope_buildings ssb
ON c.building_id = ssb.building_id
AND ssb.scope_id = '%s'
WHERE energy_id = '%s'
AND parent_id is not NULL
AND type = 'C'
""", [self.id, energy_id])
答案 2 :(得分:0)
您还需要使用%d作为第一个占位符,因为self.id将是Integer而不是String。 %d告诉字符串期望该插槽中有一个int。