使用2个排序值排序过滤器(django_filters)

时间:2018-02-01 15:25:25

标签: django django-filter django-filters

您好每个人都可以使用OrderingFilter,例如django order_by,其中包含2个排序值queryset.ordery_by('value1', value_2')

我试过了

order_by = django_filters.OrderingFilter(
        fields=(
            ('item_name', 'Items),
            ('time_from', 'Time'),
            (('value1', 'value2'), 'Value'),
        )
    )

但收到expected string or bytes-like object

2 个答案:

答案 0 :(得分:1)

OrderingFilter supports multiple ordering params if you're willing to include them in the request: my_view?order_by=value1,value2.

If you want the same result with a request that looks like my_view?order_by=values, a way I can think of to achieve that is to override OrderingFilter:

class CustomOrderingFilter(OrderingFilter):
    def filter(self, qs, value):
        if any(v == 'values' for v in value):
            qs.order_by('value1', 'value2')
        return super(CustomOrderingFilter, self).filter(qs, value)

答案 1 :(得分:0)

我为此创建了 OrderingFilterExtened https://github.com/soldovskij/OrderingFilterExtened

示例:

class UserFilter(FilterSet):
    order_by = OrderingFilterExtened(
        fields_many=(
            ('full_name', ('first_name', 'last_name'), ('-first_name', '-last_name')),
        ),
        fields=(
            ('email', 'email'),  # model field name, parameter name
            ('last_login', 'last_login'),
            ('date_joined', 'date_joined'),
        ),
    )

class UserListAPIView(UsersPermissionQuerysetMixin, generics.ListAPIView):
    queryset = User.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = UserListSerializer
    pagination_class = LimitOffsetPagination
    filterset_class = UserFilter

请求示例: api/v2/users/order_by=full_nameapi/v2/users/order_by=-full_name