Please wait...

Custom Django rest framework Ordering Filter

by in Django
class Employee(models.Model):
	name = models.CharField(max_length=255)
	salary = models.DecimalField(max_digits=10, decimal_places=2)
	user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
class CustomOrderFilter(OrderingFilter):

    def filter_queryset(self, request, queryset, view):
        queryset = super().filter_queryset(request, queryset, view)
        order_fields = []
        ordering_fields = getattr(view, 'custom_order_fields', None)
        if ordering_fields:
            params = request.query_params.get(self.ordering_param)
            if params:
                fields = [param.strip() for param in params.split(',')]
                ordering = [f for f in fields if f.lstrip('-') in ordering_fields]
                for field in ordering:
                    symbol = "-" if "-" in field else ""
                    order_fields.append(symbol + ordering_fields[field.lstrip('-')])
                if order_fields:
                    queryset = queryset.order_by(*order_fields)
        return queryset
class EmployeeViewSet(viewsets.ModelViewSet):
	queryset = Employee.objects.all()
	serializer_class = EmployeeSerializer
	filter_backends = (CustomOrderFilter,)
	custom_order_fields = {"email": "user__email"}