[Django]-Ordering Filter using 2 ordering values(django_filters)

3👍

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👍

I created OrderingFilterExtened for this purposes
https://github.com/soldovskij/OrderingFilterExtened

Example:

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

Request example:
api/v2/users/order_by=full_name or api/v2/users/order_by=-full_name

Leave a comment