如何将django中的icontains翻译成SQL语句?

时间:2009-05-02 06:30:54

标签: sql django

我想在每年中获得每月的前5名。

所以我输入了这样的代码

def query(request):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT product_style_id ,sum(price) As total_p ,sum(cast( amount as int )) AS total_a FROM jewelry_productorder  group by product_style_id ORDER BY total_p DESC LIMIT 5 " )
    output = cursor.fetchall()
    variables = RequestContext (request, {'output':output,})
    return render_to_response('top5.html', variables)

结果显示整个表格的前5名,而不是每年每月的前5名。

所以我输入这样的代码(通过添加WHERE子句)

def query(request):
    m = request.GET['month']
    y = request.GET['year']
    d = str(y+'-'+m)
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT product_style_id ,sum(price) As total_p ,sum(cast( amount as int )) AS total_a FROM jewelry_productorder WHERE due_date LIKE %s group by product_style_id ORDER BY total_p DESC LIMIT 5 " ,[d])
    output = cursor.fetchall()
    variables = RequestContext (request, {'output':output,})
    return render_to_response('top5.html', variables)

结果就像这样

/ error

中的ProgrammingError

运算符不存在:date ~~ unknown 第1行:... total_a FROM jewelry_productorder WHERE due_date LIKE E'200 ...                                                              ^ 提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

请帮帮我,我该怎么办?

1 个答案:

答案 0 :(得分:2)

Django中的

__ icontains可以使用ILIKE在SQL中编写。

示例:

SELECT ... WHERE some_column ILIKE '%some_string%'

所以你可以改写你的查询:

cursor.execute("SELECT product_style_id ,sum(price) As total_p ,sum(cast( amount as int )) AS total_a FROM jewelry_productorder WHERE due_date ILIKE %s group by product_style_id ORDER BY total_p DESC LIMIT 5", ["%%%s%%" % d])

如果您的数据库不支持ILIKE(正如我的回答评论中所指出的那样),请执行以下操作:

SELECT ... WHERE LOWER(some_column) LIKE LOWER('%some_string%')

请注意,使用LOWER可能会阻止您的数据库使用索引(如果您在该列上有索引)。

另外,请注意Django 1.1添加了聚合支持,因此您应该能够在不诉诸原始SQL的情况下进行GROUP BY查询。检查一下:http://docs.djangoproject.com/en/dev/topics/db/aggregation/