Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda