2

I want to limit the queryset returned by a ListAPIView, using the filtering technique described here.

The question is, how do I handle invalid parameters? Raising a ValidationError only works for serializers, not within the ViewSet. I'd like to let the user know that the request was invalid, rather than failing silently.

For example:

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
              try:
                  user = User.objects.get(username=username)
              except User.DoesNotExist:
                  # How do I handle this invalid parameter?
              else:
                  queryset = queryset.filter(purchaser=user)
        return queryset

2 Answers 2

5

Use the build in exceptions, since you are responding for something that was not found, use the NotFound:

from rest_framework import exceptions

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
              try:
                  user = User.objects.get(username=username)
              except User.DoesNotExist:
                  raise exceptions.NotFound(detail="Some message if you want")
              else:
                  return queryset.filter(purchaser=user)
        return queryset
Sign up to request clarification or add additional context in comments.

Comments

1

Can't you just return an empty list?

queryset = queryset.filter(purchaser__username=username)

If it is an invalid username this queryset will just be an empty queryset and DRF will return an empty list in result.

1 Comment

This question is about letting the user know that the request was invalid, rather than failing silently.

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.