0

View:

class FooViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Foo.objects.filter(state=2)
    serializer_class = FooSerializer

class BarViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Bar.objects.filter(state=2)
    serializer_class = BarSerializer

class BazViewList(generics.ListAPIView):
    queryset = Baz.objects.all()
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = BazSerializer

def list(self, request):
    queryset = Baz.objects.all()
    serializer = BazSerializer(queryset, many=True)
    return Response(serializer.data)

urls:

from django.conf.urls import include
from django.conf.urls.defaults import patterns, url
from rest_framework import routers
from rest_framework.authtoken import views as vs

router = routers.DefaultRouter()
router.register(r'Foo', views.FooViewSet)
router.register(r'Bar', views.BarViewSet)
#router.register(r'Baz', views.BazViewList)

urlpatterns = patterns('app.restapi.views',
    url(r'^v1/Baz/', BazViewList.as_view(), name='baz_view_list'),
    url(r'^v1/', include(router.urls)),
    url(r'^v1/api-token-auth/', vs.obtain_auth_token))

Now, the way it is now if I browse the v1/ endpoint (which should provide a documentation), the API root only lists the Foo and Bar, but not the Baz:

Api Root
GET /api/rest/v1/
HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, HEAD, OPTIONS

{
    "Foo": "http://localhost:8000/api/rest/v1/Foo/",
    "Bar": "http://localhost:8000/api/rest/v1/Bar/"
}
Csaba Toth
  • 10,021
  • 5
  • 75
  • 121

1 Answers1

2

The easiest way to fix this would be to change BazViewList to BazViewSet that inherits from rest_framework.mixins.ListModelMixin and rest_framework.viewsets.GenericViewSet:

from rest_framework import viewsets, mixins

class BazViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
   ...

This will set up all the internal plumbing so that BazViewSet can be registered as a router and all the magic of the router will take care of the URLs for you.

seawolf
  • 2,147
  • 3
  • 20
  • 37
  • Yeah, the code also stated that it only deals with ViewSets. So I converted it to a ViewSet and I hop I won't need any customization what ViewSet couldn't handle. – Csaba Toth Jul 23 '15 at 16:04
  • 2
    I've learned a *lot* about ViewSets recently and have basically come to the conclusion that there is nothing the ViewSet can't handle with a little creative thinking. If you need help with a specific case, post the question and message me, I'll look and guide you through it. – seawolf Jul 23 '15 at 19:12