Django: Order_by multiple fields

后端 未结 3 1024
日久生厌
日久生厌 2020-12-14 14:22

I am getting order_by fields in the form of a list. I want to order_by by multiple fields with django orm. List is like below:

orderbyList = [\'check-in\',\'         


        
相关标签:
3条回答
  • 2020-12-14 14:49

    Pass orders list in query parameters

    eg : yourdomain/?order=location&order=check-out

    orderbyList = ['check-in']  #default order
    
    if request.GET.getlist('order'):
      orderbyList = request.GET.getlist('order')
    
    modelclassinstance.objects.all().order_by(*orderbyList)
    
    
    0 讨论(0)
  • 2020-12-14 14:52

    Try something like this

    modelclassinstance.objects.order_by('check-in', 'check-out', 'location')
    

    You don't need .all() for this

    You can also define ordering in your model class

    something like

    class Meta:
           ordering = ['check-in', 'check-out', 'location']
    
    0 讨论(0)
  • 2020-12-14 14:55

    Try this:

    listOfInstance = modelclassinstance.objects.all()
    
    for askedOrder in orderbyList:
        listOfInstance = listOfInstance.order_by(askedOrder)
    
    0 讨论(0)
提交回复
热议问题