尝试检索单个资源

时间:2017-09-12 07:21:13

标签: python django django-rest-framework django-rest-viewsets

我是新的Python和Django。我创建了ViewSet如下:

API / views.py

class UserDetails(ViewSet):
"""
CREATE, SELECT, UPDATE OR DELETE
"""

def retrive(self, request, pk):
    user = self.get_object(pk)
    print(user.query)
    user = TestSerializer(user)
    return Response(user.data)

def list(self, request):
    users = TestTB.objects.all()
    print(users.query)
    serializer = TestSerializer(users, many=True)
    return Response(serializer.data)

def create(self, request):
    serializer = TestSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def update(self, request, pk):
    user = self.get_object(pk)
    serializer = TestSerializer(user, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def destroy(self, request, pk):
    user = self.get_object(pk)
    user.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

def get_object(self, pk):
    try:
        return TestTB.objects.get(pk=pk)
    except TestTB.DoesNotExist:
        raise Http404

API / urls.py

router = routers.DefaultRouter()
router.register(r'users', UserDetails, base_name='user-details')

urlpatterns = router.urls

这适用于POST请求创建新资源,GET请求获取所有资源,PUT请求更新资源和DELETE请求删除资源。但是我如何检索单一资源?当我发出http://127.0.0.1:8000/api/users/1/之类的请求而不是显示错误 -

  

{       “细节”:“方法”GET“不允许”。   }

这意味着永远不会调用UserDetails中的retrieve()方法。我知道我错过了什么,但却无法弄清楚是什么。

1 个答案:

答案 0 :(得分:3)

retrive更改为retrieve。根据@Linovia的建议,在评论中做出了回答。