2015-08-29 182 views
0

我有一個函數從html文件中調用來訂購我的書籍列表。點擊html文件中的按鈕後,book_list_title被調用,我想要顛倒順序,從下降到上升,反之亦然,但我不知道如何做到這一點。Django反向的升序/降序排列

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') 

您也可以通過order變量放到模板,並依靠其顯示的順序方向在:

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}) 
+1

如果你想顯示它相同ems列表中,您可以使用javascript重新排序,而不是重新加載頁面。關於交換機,您可以使用get請求參數或kwarg。 http://stackoverflow.com/questions/13678933/how-can-i-pass-kwargs-in-url-in-django – cdvv7788

+0

嗯我不知道我完全理解你在說什麼。如何知道要傳入的關鍵字參數。無法解決我無法保存(並稍後確定)列表是按升序還是降序排列的問題 – Max

+1

爲什麼需要保存它?當您將列表返回到您的視圖時,您將包含一個標誌,顯示它是否是asc或desc。您的Ajax提交功能然後發送相反。 –

回答

0

/books/?order=desc/books/?order=asc

並且在視圖處理此標誌的地址鏈接

{% if order == 'desc' %}/books/?order=asc{% else %}/books/?order=desc{% endif %} 
相關問題