Django:传递多个参数的RawQuerySet问题

时间:2011-05-24 00:52:07

标签: django postgresql

我用过这个问题的回答:

  

Django: making raw SQL query, passing multiple/repeated params?

但有一些问题。

我有参数:

params = {'film_id_string': 'core_film.parent_id', 'tags_params': 'comedy', 'order_by': 'core_film.title', 'content_type': '18', 'language_code': 'en'}

用于SQL查询:

query = 'SELECT DISTINCT "core_object".*, "core_film".*  FROM "core_film"  INNER JOIN "core_object" ON ("core_film"."parent_id" = "core_object"."id")  LEFT OUTER JOIN "core_objectlocalized" ON ("core_objectlocalized"."parent_id" = %(film_id_string)s) LEFT OUTER JOIN "tagging_taggeditem" ON ("tagging_taggeditem"."object_id" = "core_objectlocalized"."id") LEFT OUTER JOIN "tagging_tag" ON ("tagging_tag"."id" = "tagging_taggeditem"."tag_id")  WHERE  "tagging_tag"."name" IN (%(tags_params)s) AND "core_objectlocalized"."LANG"=%(language_code)s AND content_type_id=%(content_type)s ORDER BY %(order_by)s'

当我尝试使用RawQuerySet

films = Film.objects.raw(query, params)

我明白了:

SELECT DISTINCT "core_object".*, "core_film".*
FROM "core_film"
INNER JOIN "core_object" ON ("core_film"."parent_id" = "core_object"."id")
LEFT OUTER JOIN "core_objectlocalized" ON ("core_objectlocalized"."parent_id" = E\'core_film.parent_id\')
LEFT OUTER JOIN "tagging_taggeditem" ON ("tagging_taggeditem"."object_id" = "core_objectlocalized"."id")
LEFT OUTER JOIN "tagging_tag" ON ("tagging_tag"."id" = "tagging_taggeditem"."tag_id")
WHERE "tagging_tag"."name" IN (E\'comedy\')
  AND "core_objectlocalized"."LANG"=E\'en\'
  AND content_type_id=E\'18\'
ORDER BY E\'core_film.title\'

问题是,'E\'的每个地方都会产生类似于此的错误:

DatabaseError: invalid input syntax for integer: "core_film.parent_id"
LINE 1: ...calized" ON ("core_objectlocalized"."parent_id" = E'core_fil...

我该如何解决这个问题?

Django版本1.2.3。

修改
我无法删除引号,因为我使用字符串:

result = self.function(result, tag, "core_film.parent_id")
def function(self, objects, tags, film_id_string):

我对RawQuerySet的参数如下所示:

params = {'film_id_string': film_id_string}

当我尝试解析这个时,我得到:

LEFT OUTER JOIN "core_objectlocalized" ON ("core_objectlocalized"."parent_id" = E\'core_film.parent_id\') 

然后我遇到了

的问题
DatabaseError: invalid input syntax for integer: "core_film.parent_id"
LINE 1: ...calized" ON ("core_objectlocalized"."parent_id" = E'core_fil...

但是,当我使用字符串格式

LEFT OUTER JOIN "core_objectlocalized" ON ("core_objectlocalized"."parent_id" = %s)' % film_id_string

它有效:

LEFT OUTER JOIN "core_objectlocalized" ON ("core_objectlocalized"."parent_id" = core_film.parent_id)

我想省略SQL注入的可能性,所以基于Django docs我不想用字符串格式传递params。
我还能做什么?

1 个答案:

答案 0 :(得分:1)

Django通过转义参数来防止SQL插入。这是一个SQL语句,因此它不起作用的事实是一件好事--Django正在做它的工作。除非系统的用户将设置“film_id_string”的值,否则你所做的工作应该没问题。如果没有,那么你必须仍然使用“...%s)'%film_id_string ...”方法,但是创建自己的自定义过滤器以验证它是否是正确的允许值之一。