Answer the question
In order to leave comments, you need to log in
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
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
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question