Django: Order_by multiple fields

眉间皱痕 提交于 2019-11-27 21:10:32

问题


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?


回答1:


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



回答2:


Try this:

listOfInstance = modelclassinstance.objects.all()

for askedOrder in orderbyList:
    listOfInstance = listOfInstance.order_by(askedOrder)



回答3:


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)



来源:https://stackoverflow.com/questions/36564694/django-order-by-multiple-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!