2012-07-22 45 views
0

我正在使用django-mptt,並且卡住了。Django mptt和合並多個對象

我想獲得每個類別的所有對象與來自後代類別的所有對象。

我設法實現了我的目標,但有一個問題 - 我無法對項目進行排序,因爲它們是從多個對象生成的。

我想我的方法很糟糕。

我如何實現我的目標,並可以合併所有返回的對象並按日期排序?

查看:

def category_view(request, pk, slug, sub_pk=None, subcategory=None): 

    if not subcategory: 
     current_category = get_object_or_404(Category, pk=int(pk)) 
     adv_obj = current_category.get_descendants(include_self=True) 
     print adv_obj 

    else: 
     current_category = get_object_or_404(Category, pk=int(sub_pk)) 
     adv_obj = current_category.get_descendants(include_self=True) 


    return TemplateResponse(request, "category_view.html", {'category_details':current_category, 
                  'advert': adv_obj, 
                  }, 
          ) 

模板:

{% block content %} 
<div class="grid_8"> 
    <h2>{{category_details.name}}</h2> 
    <hr> 
    <div> 
     {% for n in advert.all %} 
     {% for p in n.advert_set.all %} 

     <div> 
      <h3>{{p.title}}</h3> 
      <span class="annoucement_detail">Kategoria: </span><a href="{{n.category.get_absolute_url}}">{{p.category.name}}</a> 
      {% if p.location %} | <span class="annoucement_detail">Miejscowość: </span>{{p.location}} 
      {% endif %} 
      <div> 
       <span class="annoucement_detail">Data dodania: </span> {{p.date_added}} | <span class="annoucement_detail">Data wygaśnięcia: </span>{{p.expiration_date}} 
      </div> 
      <div> 
       {{p.text}} 
      </div> 
     </div> 
     <hr> 
     {% endfor %} 
     {% endfor %} 
    </div> 

</div> 
{% endblock%} 

編輯:

我想出了一個主意。我將遍歷視圖中的結果並使用itertools將其鏈接起來。 我明天會檢查它是否去上班:)

回答

1

那我anwser :)

def category_view(request, pk, slug, sub_pk=None, subcategory=None): 

    advert_list = [] 

    if not subcategory: 
     current_category = get_object_or_404(Category, pk=int(pk)) 
     adv_obj = current_category.get_descendants(include_self=True) 

     for n in adv_obj: 

      for p in n.advert_set.all().order_by('-date_added'): 
       advert_list.append(p) 

     adv_obj = chain(advert_list) 

     adv_obj = sorted(adv_obj, key=operator.attrgetter('date_added')) 
     adv_obj.reverse() 


    else: 
     current_category = get_object_or_404(Category, pk=int(sub_pk)) 
     adv_obj = current_category.get_descendants(include_self=True) 

     for n in adv_obj: 

      for p in n.advert_set.all().order_by('-date_added'): 
       advert_list.append(p) 

     adv_obj = chain(advert_list) 
     adv_obj = sorted(adv_obj, key=operator.attrgetter('date_added')) 
     adv_obj.reverse() 

    return TemplateResponse(request, "category_view.html", {'category_details':current_category, 
                  'advert': adv_obj, 
                  }, 
          )