1

I have users endpoint working fine, with various FilterBackends. I'm trying to add in a new filter to be able to pass in a list of ids such as ?ids=1,5,7 and returning only those users.

I have found the following filter which accomplishes that, but then breaks my other filters:

class ListFilter(Filter):
    def filter(self, qs, value):
        if not value:
            return qs

        self.lookup_type = 'in'
        values = value.split(',')
        return super(ListFilter, self).filter(qs, values)


class UserListFilter(FilterSet):
    ids = ListFilter(name='id')

    class Meta:
        model = get_user_model()
        fields = ['ids']


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter, InterestsFilter)
    filter_fields = ('username', 'native_language', 'country', 'interests',)
    ordering_fields = ('username',)
    search_fields = ('first_name', 'last_name')
    filter_class = UserListFilter

Before adding in this custom filter_class, all the filter backends work fine, but then after adding in the filter_class, it breaks them all, but I can then filter by a list of ids.

In the filtering docs they give an example using both backends and filter, so I would think this should work, but it's something wrong with my code. Any ideas?

1
  • I had a similar issue when tried to mix filter_backends with filter_class. But then I found that django-filter has also a capability of ordering results and this is what I needed, so I just defined ordering filter using django-filter and stopped using filter_backends on that class. Commented Aug 18, 2016 at 23:50

1 Answer 1

3

You can override the get_queryset method and achieve the functionality of filtering by ids.

def get_queryset(self):
    ids = self.request.query_params.get('ids') # List of ids
    if ids:
        return User.objects.all().filter(id__in=ids) # returned queryset filtered by ids
    return User.objects.all() # return whole queryset
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! That's much cleaner. 'ids[]' didn't work for me btw django 1.8 drf 3.1.2, needed to change to 'ids' and then split the string

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.