【问题标题】:Django reverse order of ascending/descending listDjango逆序升序/降序列表
【发布时间】:2015-08-29 21:29:57
【问题描述】:

我有一个从 html 文件调用的函数来订购我的书单。单击 html 文件中的按钮后,将调用 book_list_title,我想将顺序从降序反转为升序,反之亦然,但不知道如何执行此操作。

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

【问题讨论】:

  • 如果您想在列表中显示相同的项目,您可以使用 javascript 重新排序,而不是重新加载页面。关于switch,可以使用get请求参数或者kwarg。 stackoverflow.com/questions/13678933/…
  • 嗯我不确定我完全理解你在说什么。我怎么知道要传入什么关键字参数。不能解决我无法保存(并稍后确定)列表是按升序还是降序排序的问题
  • 为什么需要保存?当您将列表返回到您的视图时,您会包含一个标志,显示它是 asc 还是 desc。然后您的 Ajax 提交函数发送相反的内容。

标签: django django-views


【解决方案1】:

使用/books/?order=desc/books/?order=asc 等地址

在你看来处理这个标志:

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 变量传递到模板中,并根据它在链接中显示顺序方向

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2018-01-14
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多