我用的回答:Django的:RawQuerySet問題傳遞多個PARAMS從這個問題
Django: making raw SQL query, passing multiple/repeated params?
,但有一些問題。
我有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是這樣的:
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)
我想ommit SQL注入的posibility,所以基礎上Django docs我不想傳遞字符串格式的參數。
我還能做什麼?
嘗試從字典中的值中刪除單引號。這是如何在舊的舊帖子,它似乎試圖逃避它們的數據庫,這是什麼導致E \ ... \。 – solartic 2011-05-24 01:30:05
@solartic,謝謝你的建議。部分我刪除了引號,但問題仍然存在。我還爲我的問題添加了額外的信息。 – 2011-05-24 12:48:32
@dasm老實說,額外的信息讓我感到困惑,但無論如何,對我而言,錯誤是說「core_objectlocalized」。「parent_id」的整數值是預期的,並且您正在傳遞一個字符串?在你最後的代碼塊中,你將它用作變量而不是我猜測爲你工作的刺痛。 – solartic 2011-05-24 22:55:18