B
B
borisovdenis2017-09-10 13:15:42
Django
borisovdenis, 2017-09-10 13:15:42

How to add filtering and sorting to function-based views?

There is a Django project. This project has a REST API implemented with django-rest framework and function-based views. There is a task: in a very short time, add filtering and sorting to the functions that process GET requests. I found a solution to this problem for class-based, but since the deadlines are very tight to rewrite all views using classes - not the best idea.
Please tell me how to solve this problem using the existing function-based views.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Oskin, 2017-09-10
@Oskin1

def order_qs(request, qs):
    order = request.GET.get('order')
    sort = request.GET.get('sort')
    if order == 'ASC':
        return qs.order_by(sort)
    elif order == 'DESC':
        return qs.order_by('-' + sort)
    else:
        return qs


def construct_page(request, qs):
    """ Builds the list-view with pagination """
    limit = request.GET.get('limit', 10)
    page_num = request.GET.get('page')
    paginator = Paginator(order_qs(request, qs), limit)
    try:
        page = paginator.page(page_num)
    except PageNotAnInteger:
        page = paginator.page(1)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)
    return page

views.py:
def category_detail_view(request, cat_slug=None):
    category = get_object_or_404(Category, slug=cat_slug)
    ctx = {}
    ctx['category'] = category
    ctx['products'] = construct_page(request, Product.objects.filter(category=category))
    return render(request, 'main/category_detail.html', ctx)

filtering in the same way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question