2013-04-24 1 views
0

재귀 함수의 출력에서 ​​단일 쿼리 세트를 얻으려고하고 있는데 성능 문제가 발생합니다.django querysets 일괄 조합

기본적으로 개별 쿼리 세트를 결합하려는 시도는 처리에 소요되는 시간을 두 배로 늘리는 것 (구현 때문에 예상 했음)이지만 더 효율적으로 수행 할 수 있는지 궁금해하고있었습니다.

def intersect(self, list_of_querysets): 
    combined = list_of_querysets[0] 
    for queryset in list_of_querysets: 
     combined = combined | queryset 
    return [combined] 


def _get_template_folders(self, template_folder_list): 
    """ 
    :rtype : list 
    """ 

    parents = [] 
    for template_folder in template_folder_list: 
     if not TemplateFolder.objects.filter(pk=template_folder).exists(): 
      continue 
     templates = TemplateFolder.objects.filter(pk=template_folder) 
     for template in templates: 

      parent_folders = self._get_template_folders([template.template_folder_parent_id]) 
      if parent_folders is not None: 
       parents.extend(parent_folders) 

     if templates is not None: 
      parents.append(templates) 
    if parents: 
     return parents 
    else: 
     return None 

template_folders_list = self.intersect(self._get_template_folders(template_folder_list)) 

답변

1

귀하의 모델을 보지 않고도 말하기는 어렵지만, 귀하의 TemplateFolder 모델은 일종의 나무 구조입니다. 그렇다면 MPTT와 같은 것을 사용하여 데이터베이스에 저장해야합니다. 왼쪽 및 오른쪽 노드 값과 관련하여 트리 구조에 대한 설명에 각 행에 주석을 달아주는 알고리즘입니다. 특정 부모는 매우 효율적입니다. 훌륭한 장고 구현은 django-mptt입니다.

+0

get_template_folders가 자신에게 부과 된 제한 사항만큼 효율적이라고 언급 했어야합니다. 내가 뭘 찾고 있었는지 get_template_folders가 많은 중복 코드를 뽑아 내면서 코드의 중복 제거 부분을 빠르게하기 위해 intersect와 결합하는 것이었다. django-mptt와 같은 것을 사용하고 싶지만 불행히도 우리는 데이터베이스 테이블을 설정 한 다른 응용 프로그램과 매우 긴밀하게 결합되어 있습니다. 우리는 그걸로 인터페이스를하고 있습니다 ...보세요. 고마워. – Jharwood