Home > Software design >  Django DRF api does not return any value
Django DRF api does not return any value

Time:10-12

I am trying to create my first api using Django rest framework DRF. Here is my code:

in views.py :

class PostViewSet(viewsets.ModelViewSet):

    # permission_classes = [IsAuthenticated]

    @action(detail=True, methods=['GET'])
    def queryset(self, request, pk=None):
        try:
            queryset = Post.objects.get(post_id=pk)
        except Analysis.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if request.method == 'GET':
            serializer = PostSerializer(queryset)
            return Response(serializer.data)

and in urls.py:

router = DefaultRouter()
router.register(r'api/post/<int:pk>/post_analysis/', PostViewSet, basename='app_name')
urlpatterns = router.urls

However this raises an error that

The current path, api/post/698/post_analysis/, didn't match any of these. or Not Found: /api/post/698/post_analysis/

But when I change url as follows, it returns none:

PostView = PostViewSet.as_view({
    'get': 'retrieve'
})

urlpatterns = format_suffix_patterns([
  path('api/post/698/post_analysis/', PostView, name='app_name')
])

result is this:

{
    "detail": "Not found."
}

I noticed that the queryset() function of PostViewSet class is not being read.

CodePudding user response:

I would try implementing the sample ModelViewSet from the DRF documentation first and see if that works. For example:

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]

I'm no DRF expert, but your code looks quite different from the sample. For example, I'm not sure why you have an @action decorator on a queryset method, and also if you do use the queryset explicitly then I think you need to use the .all() or .filter() manager methods which generate querysets, not .get() which returns a single object. But if you have correctly defined your Serializer class then I believe the queryset is taken from the model you used to define the PostSerializer. ie:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post

CodePudding user response:

Try modifying your urls.py file as follows:

router = routers.DefaultRouter()
urlpatterns = [
    path('api/post/<int:pk>/post_analysis/', include(router.urls)),   

]

It may be a problem configuring the urls

  • Related