Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - What base_name parameter do I need in my route to make this Django API work?

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 Model looks like this:

class MyObject(models.Model):
    name = models.TextField()

My Serializer looks like this:

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

My Viewset looks like this:

class MyObjectsViewSet(viewsets.ViewSet):

    def retrieve(self,request,pk=None):
        queryset = MyObjects.objects.get(pk=pk).customMyObjectList()

        if not queryset:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            serializer = MyObjectSerializer(queryset)
            return Response(serializer.data,status=status.HTTP_200_OK)

When I hit /api/myObjects/60/ I get the following error:

base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.

I understand from here that I need a base_name parameter on my route. But from the docs, it is unclear to me what that value of that base_name parameter should be. Can someone please tell me what the route should look like with the base_name?

question from:https://stackoverflow.com/questions/22083090/what-base-name-parameter-do-i-need-in-my-route-to-make-this-django-api-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try doing this in your urls.py. The third parameter 'Person' can be anything you want.

router.register(r'person/food', views.PersonViewSet, 'Person')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...