使用raw(...)进行SQL格式化/转义注入

时间:2018-11-07 23:10:40

标签: python mysql sql django

我在Django中使用查询。通常,我通常直接在sql连接器中执行此操作,但有时我使用raw(...)方法,例如:

items_from_master = list(ItemMaster.objects.raw(
    """SELECT * FROM main_itemmaster WHERE 
       (content_type_id != 'TV Season') AND (MATCH(name) against('%s')) LIMIT 20
       UNION 
       SELECT * FROM main_itemmaster WHERE name='%s'
       ORDER BY imdb_votes DESC LIMIT 30""" % (q,q)))

有没有办法在这里转义字符串?例如,类似cursor.execute(sql, params)的东西?

1 个答案:

答案 0 :(得分:1)

raw(...) supports a params argument正是这种情况。

请注意从原始查询中删除引号:

items_from_master = list(
    ItemMaster.objects.raw(
        """
        SELECT * FROM main_itemmaster WHERE 
        (content_type_id != 'TV Season') AND (MATCH(name) against(%s)) LIMIT 20
        UNION 
        SELECT * FROM main_itemmaster WHERE name=%s
        ORDER BY imdb_votes DESC LIMIT 30
        """,
        [q, q],
    ),
)

这也可以使用字典,在像您这样多次使用一个值的情况下,字典会更干净:

items_from_master = list(
    ItemMaster.objects.raw(
        """
        SELECT * FROM main_itemmaster WHERE 
        (content_type_id != 'TV Season') AND (MATCH(name) against(%(q)s)) LIMIT 20
        UNION 
        SELECT * FROM main_itemmaster WHERE name=%(q)s
        ORDER BY imdb_votes DESC LIMIT 30
        """,
        {"q": q},
    ),
)