如何使用SQL通配符%和Queryset extra>选择?

时间:2010-04-21 22:37:02

标签: mysql django django-queryset

我在视图中使用了extra()修饰符。

(见http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none

以下是代码:

def viewname(request)
    ...
    exact_matchstrings=[]
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + "')")
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + '\%' +  "')")

    extraquerystring = " + ".join(exact_matchstrings)

    return_queryset = return_queryset.extra(
        select = { 'match_weight': extraquerystring },
        )

上面的两个附加语句几乎完全相同,只是第二个添加% SQL通配符。这导致错误;没有%的语句没有问题。 %发生了什么?我很惊讶django认为这个字符没有定义,因为它是在SQL规范中。例如,以下SQL语句执行得很好:

select (first_name like "Car") + (first_name like "Car%") from accountprofile;

但是尝试通过我的视图代码中的extra()修饰符运行它并评估生成的查询集会给我一个错误。我认为“%”需要转义,所以我已经尝试过了。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我们自己用LIKE做了一个额外的查询。要逃避%,您需要执行%%

Percentage sign not working

答案 1 :(得分:0)

看起来你错过了第二个字符串中的一些引号。除非django要求,否则我不确定你是否需要逃避百分比(%)。

_matchstrings.append("(accountprofile.first_name LIKE '" + term + "%" +  "')")