danny
danny

Reputation: 1103

Django: order_by multiple fields

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

orderbyList = ['check-in','check-out','location']

I am writing a query like this:

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

Everything I'm expecting in a list is dynamic. I don't have predefined set of data. Could some tell me how to write a Django ORM with this?

Upvotes: 97

Views: 96299

Answers (6)

Dinesh Kumar
Dinesh Kumar

Reputation: 27

modelclassinstance.objects.filter(anyfield='value').order_by('check-in', 'check-out', 'location')

Upvotes: 3

Chilusoft
Chilusoft

Reputation: 419

You should pass a list of stringified arguments of the database table columns (as specified by your ORM in the respective models.py file) to the .order_by() method on the return query set like so. shifts = Shift.objects.order_by('start_time', 'employee_first_name'). By notation,.order_by(**args), will help you remember that takes an arbitrary number of arguments.

Upvotes: 0

Sawan Chauhan
Sawan Chauhan

Reputation: 791

Pass orders list in query parameters

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

default_order = ['check-in']  #default order
order = request.GET.getlist('order', default_order)
modelclassinstance.objects.all().order_by(*orderbyList)

Upvotes: 12

TOXIC dz
TOXIC dz

Reputation: 1

What you have to do is chain the querySets, in other words:

classExample.objects.all().order_by(field1).order_by(field2)...

Upvotes: -7

MicroCheapFx
MicroCheapFx

Reputation: 402

Try this:

listOfInstance = modelclassinstance.objects.all()

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

Upvotes: -3

burning
burning

Reputation: 2586

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

Upvotes: 162

Related Questions