开发者

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 ord开发者_StackOverflowering.

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).


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'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜