2009-05-02 7 views
0

매월 의 판매 가격 상위 5 개를 받고 싶습니다.은 인 입니다. django에서 icontains를 SQL 문으로 변환하는 방법은 무엇입니까?

그래서 나는 매년 각 달의 상위 5 대신 전체 테이블의 상위 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) 

결과처럼 코드에 넣어.

그래서 내가 (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) 

결과는

연산자가 존재하지 않는에서이

ProgrammingError/쿼리처럼 나왔다 : 날짜 ~ ~ 알 수 없음 LINE 1 : ... total_a FROM jewelry_productder where due_date LIKE E'200 ... ^ 힌트 : 주어진 이름 및 인수 유형과 일치하는 연산자가 없습니다. 명시 적 타입 캐스트를 추가해야 할 수도 있습니다.

도와주세요, 어떻게해야합니까 ??

+0

어떤 데이터베이스를 사용하고 있습니까? – ibz

답변

2

장고에서 __icontains는 ILIKE를 사용하여 SQL로 작성할 수 있습니다.

예 : 귀하의 DB는 ILIKE을 (내 대답에 코멘트에서 지적)를 지원하지 않는 경우

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]) 

, 뭔가를 할 : 같은

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

그래서 당신은 당신의 쿼리를 다시 작성할 수 있습니다 당신이 색인이있는 경우 (인덱스를 사용하여 DB를하지 못할 수도 있습니다, LOWER 사용하는 것을

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

참고 :이 같은 그 칼럼에).

또한 Django 1.1은 집계 지원을 추가 했으므로 원시 SQL을 사용하지 않고 GROUP BY 쿼리를 작성할 수 있어야합니다. 이것을 확인하십시오 : http://docs.djangoproject.com/en/dev/topics/db/aggregation/

+1

모든 데이터베이스에서 ILIKE를 사용할 수있는 것은 아닙니다. –

관련 문제