Django: Order_by multiple fields

2020-02-09 00:48发布

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','check-out','location']

I am writing a query is like:

modelclassinstance.objects.all().order_by(*orderbyList)

Everything i am expecting in a list is dynamic. I don't have predifined set of data.Could some tell me how to write a django ORM with this?

3条回答
成全新的幸福
2楼-- · 2020-02-09 01:26

Try this:

listOfInstance = modelclassinstance.objects.all()

for askedOrder in orderbyList:
    listOfInstance = listOfInstance.order_by(askedOrder)
查看更多
闹够了就滚
3楼-- · 2020-02-09 01:34

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']
查看更多
神经病院院长
4楼-- · 2020-02-09 01:43

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)

查看更多
登录 后发表回答