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
- [Django]-GenericForeignKey or ForeignKey
- [Django]-Serializer.is_valid() failing though `required=False` – Django REST Framework
- [Django]-Django Send emails to all users in the database table
- [Django]-Django-queryset get one object per field=foo
- [Django]-Where to instantiate a client for an external service in Django?
Source:stackexchange.com