我是新的 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/
,它显示错误 -
{ "detail": "方法 \"GET\" 不允许。" }
这意味着永远不会调用 UserDetails 中的 retrieve() 方法。我知道我错过了一些东西,但无法弄清楚是什么。