Saqib Ali
Saqib Ali

Reputation: 12605

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

I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions here.

My Route looks like this in myApp's url.py:

from rest_framework import routers
router = routers.DefaultRouter()    router.register(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsViewSet)
url(r'^api/', include(router.urls)),

My Serializer looks like this:

class MyObjectSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MyObject
    fields = ('id', 'name',)

My Viewset looks like this:

class MyObjectsViewSet(viewsets.ModelViewSet):
    queryset = MyObjects.objects.get(pk=self.kwargs['id'])
    serializer_class = MyObjectSerializer

When I hit /api/myObjects/60/ I get the following error from the first line of the Viewset:

name 'self' is not defined

Why?? How do I grab the ID of 60 in my viewset and get fetch the MyObject with that ID?

Upvotes: 3

Views: 13900

Answers (4)

wilcoln
wilcoln

Reputation: 73

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

Upvotes: 3

Eric Lee
Eric Lee

Reputation: 732

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

Upvotes: 7

Scott Woodall
Scott Woodall

Reputation: 10686

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.

Upvotes: 2

Heikki Toivonen
Heikki Toivonen

Reputation: 31150

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.

Upvotes: 0

Related Questions