【问题标题】:ordering QuerySet in lowercase reverse order以小写逆序排列 QuerySet
【发布时间】:2015-08-26 01:14:31
【问题描述】:

views.py 中为我的 django 项目定义了以下函数。我遇到的唯一问题是按小写顺序(即Lower())和相反的顺序(即'-title'而不是'title')对所有书籍进行排序。我可以选择其中之一,但不能同时订购。

我收到以下错误:

Cannot resolve keyword '-title' into field. Choices are: author, date_modified, title

def book_list_title(request):

    all_entries = Book.objects.all().order_by(Lower('-title'))
    books_list=[]

    //Do stuff to create a proper list of books

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

【问题讨论】:

    标签: python django django-views django-queryset


    【解决方案1】:

    通过documentation of order_by,您应该可以在Lower() 上使用desc()

    all_entries = Book.objects.all().order_by(Lower('title').desc())
    

    【讨论】:

    • 这是最好的答案
    【解决方案2】:

    尝试使用Query Expressions

    from django.db.models import Func, F
    
    Book.objects.all().annotate(title_lower=Func(F('title'), function='LOWER')).order_by('-title_lower')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2019-02-06
      相关资源
      最近更新 更多