简体   繁体   中英

How can I derive a Django queryset to a REST request based on API parameter?

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 ][1].

I want to make it such that when the API endpoint /api/myObject/60/ is hit, it should return lookup myObject with ID==60 and then return the value of getCustomMyObjectsList() which is a method of myObject. But I've been going around in circles for 2-3 days trying to figure how to do it.

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']).getCustomMyObjectsList()
    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? Can someone please show me the exact code I need to write in MyObjectViewSet()?

Thanks

self is a reference to the object instance and not available when defining class variables. You should override the get_queryset method to achieve your goal, where the request object is available by accessing self.request .

For more details you can check out http://www.django-rest-framework.org/api-guide/filtering

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM