2012-04-05 3 views
0

모든 검색 조건을 구성하는 13 개의 체크 박스 그룹이있는 양식이 있습니다 ... ALL 또는 ANY에 대한 라디오 버튼 쌍이 추가 된 것을 제외하고는 . Django any()와 querysets의 all() 찾기

내가 좋아하는 우아한 뭔가 도망 기대했다 :

priority_ids = request.GET.getlist("priority") # checkboxes 
collection = request.GET.get("collection") # radio buttons 
priorities = [] 
for priority_id in priority_ids: 
    priorities.append(Q(focus__priority=priority_id)) 
if (collection == "any"): qset = any(priorities) 
elif (collection == "all"): qset = all(priorities) 

그러나, 어떤() 모든()는 부울이 아닌 내가 필터에서 사용할 수있는 검색어 세트를 돌려줍니다. "Q (...) | Q (...) | Q (...)"또는 "Q (...) & Q (...)와 동등한"모든 "또는"모두 "를 원합니다. .) & Q (...) "어디서나 1에서 13까지의 기준.

답변

1

장고가해야 할 일은 없습니다. Q -s를 &|과 간단하게 결합하거나보다 컴팩트 한 방법으로 reduce으로 결합하면됩니다.

용어에 관해서는 Q을 쿼리 세트라고 부르는 것 같지만 그렇지 않습니다. 그것은 queryset에 대한 필터입니다. 다음과 같은 뭔가 작업을해야합니다 : 귀하의`lambda`s 각각 operator.or_`과`operator.and_`,`으로 대체 될 수

priority_ids = request.GET.getlist("priority") 
collection = request.GET.get("collection") 
priority_filters = [] 
for priority_id in priority_ids: 
    priority_filters.append(Q(focus__priority=priority_id)) 

base_qs = SomeModel.objects.all() 

if collection == "any": 
    filtered_qset = base_qs.filter(reduce(operator.or_, priority_filters)) 
elif collection == "all": 
    filtered_qset = base_qs.filter(reduce(operator.and_, priority_filters)) 
+1

참고. – Dougal

+0

+1,':) –

+0

을 지적 해 주셔서 감사합니다는'any' 경우는 아마도 수 '__in' 검색 유형 ('SomeModel.objects.filter (focus__priority__in = priority_ids)')을 사용하여 처리됩니다. 나는 당신이'all'을 위해서 이렇게해야한다고 생각합니다. – Dougal