[Django]-How can I grab the ID passed to a Django REST API?

7πŸ‘

βœ…

I would use ViewSet as oppose to ModelViewSet. The code below should do what you need unless there is a strong reason to use ModelViewSet. If you go to the URL of say http://yourdomain/yourmodel/10 the pk variable will have a value of 10.

class YourModelViewSet(viewsets.ViewSet):

     def retrieve(self,request,pk=None):
         u = request.user
         queryset = YourModel.objects.filter(user=u,pk=pk)
         if not queryset:
             return Response(status=status.HTTP_400_BAD_REQUEST)
         else:
             serializer = YourModelSerializer(queryset)
             return Response(serializer.data,status=status.HTTP_200_OK)

Thanks – Hope it helps

πŸ‘€Eric Lee

2πŸ‘

Since you’re using viewsets.ModelViewSet Django Rest Framework handles all the filtering of specific objects for you. Change your queryset property to MyObjects.objects.all().

Overriding queryset as others suggested will break the /myObjects/ route because the id does not exist.

πŸ‘€Scott Woodall

2πŸ‘

If you want (or need) to stick with viewsets.ModelViewSet, you can still access the id from the kwargs argument of the action methods.

class MyObjectViewSet(viewsets.ModelViewSet):

     def update(self, request, *args, **kwargs):
        obj_id = kwargs['pk']
        obj = MyObject.objects.get(pk=obj_id)
        # Do your thing
        # Send back response
πŸ‘€wilcoln

0πŸ‘

Your logger line is referencing self, but there is no self in that context (you are at class level, not inside a method). Try removing the logger line.

Leave a comment