2009-07-16 1 views
2

감사 :관련 객체를 얻는 방법 Django의 extra(). values ​​() 호출에서? 장고보기에서 쿼리에 의해이 내가 쉽게 계산 할 수 있어요 포스트 및 그룹에

동전의 종류와 얼굴 값 목록을 표시하고 내가 내 응용 프로그램에서하고 있어요

Django equivalent for count and group by

국가에 대한 내 데이터베이스에서 사용할 수 있으므로 영국에서 동전은 "1 farthing"또는 "6 pence"의 액면가를 가질 수 있습니다. face_value은 6이며, currency_type은 관련 테이블에 저장된 "펜스"입니다.

def coins_by_country(request, country_name): 
    country = Country.objects.get(name=country_name) 
    coin_values = Collectible.objects.filter(country=country.id, type=1).extra(select={'count': 'count(1)'}, 
           order_by=['-count']).values('count', 'face_value', 'currency_type') 
    coin_values.query.group_by = ['currency_type_id', 'face_value'] 
    return render_to_response('icollectit/coins_by_country.html', {'coin_values': coin_values, 'country': country }) 

currency_type_id이 수는 외래 키 필드에 저장된 건너 온다 (즉, 4) :

나는이 길의 나에게 90 %를 얻을 내보기에 다음과 같은 코드가 있습니다. 내가하고 싶은 일은 쿼리의 일부로 참조하는 실제 개체를 검색하는 것입니다 (통화 모델이므로 내 서식 파일에 Currency.name 필드를 가져올 수 있습니다).

어떻게해야할까요?

답변

1

select_related() 나를 매우 사랑 받고 있지만, 그것은 나를 내가 group_by 절에 선택한 모든 필드를 추가하고 싶었 :

함께 퍼팅, 당신은 얻을.

그래서 select_related() 뒤에 values()을 추가하려고했습니다. 안돼. 그런 다음 쿼리의 다른 위치에서 각각의 다양한 순열을 시도했습니다. 닫기지만, 아주.

SQL 쿼리를 작성하는 방법을 이미 알고 있으므로 원시 SQL을 "wimping out"하고 그냥 사용했습니다.

def coins_by_country(request, country_name): 
    country = get_object_or_404(Country, name=country_name) 
    cursor = connection.cursor() 
    cursor.execute('SELECT count(*), face_value, collection_currency.name FROM collection_collectible, collection_currency WHERE collection_collectible.currency_type_id = collection_currency.id AND country_id=%s AND type=1 group by face_value, collection_currency.name', [country.id]) 
    coin_values = cursor.fetchall() 
    return render_to_response('icollectit/coins_by_country.html', {'coin_values': coin_values, 'country': country }) 

장고의 검색어 언어 정확한 쿼리가 내가 알고 싶은데요 표현 할 수있는 방법이 있다면. 나는 SQL이 2 개의 컬럼에 의해 카운트되고 그룹화되는 것이 매우 드물지 않다는 것을 상상한다. 그래서 깨끗한 방법이 없다면 놀랄 것이다.

0

은 당신이 select_related 봤어() http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4

나는 다음 coin_values.currency.name을 갈 수 잘 작동하는 것 같다 많이 사용.

나는 국가 = country.id를 필터에 넣을 필요가 있다고 생각하지 않지만 나라가 적지 만 적은 타이핑 이외의 다른 점은 무엇인지 모르겠습니다.

2

values()으로는 수행 할 수 없습니다. 그러나 이것을 사용할 필요는 없습니다. 실제 Collectible 개체를 가져올 수 있으며 각 개체는 관련 링크 개체가 될 currency_type 특성을 갖습니다.

justinhamade가 암시 하듯이 select_related()을 사용하면 데이터베이스 쿼리 수를 줄일 수 있습니다.

coin_values = Collectible.objects.filter(country=country.id, 
        type=1).extra(
        select={'count': 'count(1)'}, 
        order_by=['-count'] 
       ).select_related() 
관련 문제