1

Is there a way to add a filter to queryset for a specific ordering field like "created" in OrderingFilter? I want to have this filter for ordering:

F('created').desc(nulls_last=True)

Here is my code:

class ProductFilter(filters.FilterSet):
    ordering = filters.OrderingFilter(fields=['price', 'created'])

    class Meta:
        model = Product
1
  • In class Meta you must to have fields property and pass all fields that you want to filter . There you can define extra fields too Commented Nov 2, 2020 at 6:23

1 Answer 1

2

This worked for me:

class NullsLastOrderingFilter(filters.OrderingFilter):
    def filter(self, qs, value):
        if value in ([], (), {}, '', None):
            return qs

        ordering = [self.get_ordering_value(param) for param in value]

        def filter_object(x):
            return F(x[1:]).desc(
                nulls_last=True
            ) if x[0] == '-' else F(x).asc(
                nulls_last=True
            )

        if ordering:
            ordering = map(filter_object, ordering)
            queryset = qs.order_by(*ordering)

        return queryset


class ProductFilter(filters.FilterSet):
    ordering = NullsLastOrderingFilter(fields=['price', 'created'])

    class Meta:
        model = Product
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.