[Answer]-Django mptt and merging multiple objects

1👍

Thats my 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,
                                                           },
                            )
👤Efrin

Leave a comment