如何在Django中将几个用户定义的字段传递给order_by() ?

时间:2021-01-21 12:56:50

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

是的,我可以将字符串分割为',然后创建一个值的元组,但是order_by需要*field_names(而不是元组)。

1 个解决方案

#1


2  

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:

Python有你的支持。如果要将元组中的所有项作为参数传递给函数,可以将元组传递到函数中,并在其前面加上星号*,如下所示:

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

#1


2  

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:

Python有你的支持。如果要将元组中的所有项作为参数传递给函数,可以将元组传递到函数中,并在其前面加上星号*,如下所示:

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