1

I want to create a viewset/apiview with a path like this: list/<slug:entry>/ that once I provide the entry it will check if that entry exists in the database.

*Note: on list/ I have a path to a ViewSet. I wonder if I could change the id with the specific field that I want to check, so I could see if the entry exists or not, but I want to keep the id as it is, so

I tried:

class CheckCouponAPIView(APIView):
    def get(self, request, format=None):
        try:
            Coupon.objects.get(coupon=self.kwargs.get('coupon'))
        except Coupon.DoesNotExist:
            return Response(data={'message': False})
        else:
            return Response(data={'message': True})

But I got an error: get() got an unexpected keyword argument 'coupon'.

Here's the path: path('check/<slug:coupon>/', CheckCouponAPIView.as_view()),

Is there any good practice that I could apply in my situation?

1 Answer 1

1

What about trying something like this,

class CheckCouponAPIView(viewsets.ModelViewSet):
    # other fields
    lookup_field = 'slug'


From the official DRF Doc,

lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to pk

Sign up to request clarification or add additional context in comments.

2 Comments

I tried it on Serializer for whatever reason. Thanks.
You don't have to do it elsewhere because it can be done with just lookup_field and it's more simplified

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.