Max
Max

Reputation: 2162

Django reverse order of ascending/descending list

I have a function that gets called from an html file to order my list of books. Upon clicking a button in the html file, book_list_title gets called and I want to reverse the order from either descending to ascending or vice versa but am not sure how to do this.

def book_list_title(request):

    if( /* Ordered descending switch to ascending */):
        all_entries = Book.objects.all().order_by('-title')

    else if( /* Ordered in reverse then switch to descending */):
        all_entries = Book.objects.all().order_by('title')

    books_list=[]

    //Do stuff to create a proper list of books

    return render(request,'books_app/books_list.html', {'books_list':books_list})

Upvotes: 0

Views: 1490

Answers (1)

Yuri Kriachko
Yuri Kriachko

Reputation: 294

Use addresses like /books/?order=desc and /books/?order=asc

And in your view handle this flag:

def book_list_title(request):
    order = request.GET.get('order', 'desc')

    all_entries = Book.objects.all()

    if(order == 'desc'):
        all_entries = all_entries.order_by('-title')

    elif(order == 'asc'):
        all_entries = all_entries.order_by('title')

You can also pass order variable into template and depends on it show direction of order in the link

{% if order == 'desc' %}/books/?order=asc{% else %}/books/?order=desc{% endif %}

Upvotes: 1

Related Questions