aemdy
aemdy

Reputation: 3802

How can I pass several user-defined fields to order_by() in Django?

Good afternoon,

I'd like to make some of my page content available to sort by users themselves. I create a user-friendly form and after submitting I get the values needed for ordering.

For example (shoes):

ordering_string = "size,-price"

I write this string to my database so that users will no longer need to set these values again.

Now, how should I pass these arguments in a format like...

shoes = ShoesModel.objects.some_kind_of_filter.order_by('size', '-price')

Yes, I can split the string by ',' and then make a tuple of values, but order_by demands *field_names (not a tuple).

Upvotes: 2

Views: 598

Answers (1)

Paul D. Waite
Paul D. Waite

Reputation: 98786

Python has your back here. If you want to pass all the items in a tuple to a function as arguments, you can pass the tuple into the function with an asterisk * in front of it, like this:

shoes = ShoesModel.objects.some_kind_of_filter.order_by(*('size', '-price'))

Upvotes: 4

Related Questions