How can I grab the API parameter in a Django views

2019-04-19 22:42发布

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 mySites url.py:

router.register(r'myObjects', 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.all()
    serializer_class = MyObjectSerializer

When I hit the API /api/myObjects/ it gives me a listing of all the myObject models. When I hit the API /api/myObjects/60/ it gives me only the myObject with id == 60. Great so far!

However, I want to change the logic of MyObjectsViewSet() such that I can manipulate/change what it returns when I hit /api/myObjects/60/. So instead of doing MyObjects.objects.all() I want to do something more complex based on the myObject ID of 60. But how can I do that?? In this viewset, how can I grab that number 60? It is not passed in as an argument. But I really need it!

2条回答
混吃等死
2楼-- · 2019-04-19 23:11

I think you can update your view for multiple operations such as

class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
                        mixins.UpdateModelMixin,
                        generics.SingleObjectAPIView):
"""
Concrete view for retrieving or updating a model instance.
FIXME: the newest version of rest_framework has this class
"""

def get(self, request, *args, **kwargs):
    return self.retrieve(request, *args, **kwargs)

def put(self, request, *args, **kwargs):
    return self.update(request, *args, **kwargs)

def create(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs)

Please watch this tutorial it will help you to understand the REST framework.

查看更多
Melony?
3楼-- · 2019-04-19 23:18

In your router, register one more url with:

router.register(r'myObjects/(?P<id>\d+)', views.MyObjectsViewSet)

and in your viewset you can grab the id with:

self.kwargs['id']

Ref: http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url

查看更多
登录 后发表回答