Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Django DRF api does not return any value

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.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório

0

I could solved the problem with the help of both provided answers as follows:

in views.py:

class PostViewSet(viewsets.ModelViewSet):
    
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]

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

and in urls.py:

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

]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda