Vassiliy Vorobyov Vassiliy Vorobyov - 6 months ago 67
Python Question

Error while initializing rest framework urls

I'm refactoring my REST API now. After using

router
instead of direct urls I can't launch my project. Where am I wrong?

Error:

TypeError: as_view() takes exactly 1 argument (3 given)


models.py:

class Device(models.Model):
...

class Measure(models.Model):
device = models.ForeignKey(Device)
...

class PeriodAverage(models.Model):
measure = models.ForeignKey(Measure)


urls.py:

router = routers.DefaultRouter()
router.register(r'devices', views.DevicesList)
router.register(r'devices/{pk}/measures', views.MeasuresList, 'Measure')
router.register(r'measures/{pk}/averages', views.PeriodAveragesList, 'Average')

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
]


views.py:

class DevicesList(viewsets.ModelViewSet):
queryset = Device.objects.all()
serializer_class = serializers.DeviceSerializer


class MeasuresList(viewsets.ModelViewSet):
serializer_class = serializers.MeasureSerializer

def get_queryset(self):
...


class PeriodAveragesList(ListAPIView):
serializer_class = serializers.PeriodAverageSerializer

def get_queryset(self):
...

Answer

Routers work with ViewSets. Your PeriodAveragesList extends ListAPIView, which is a class based view, not a ViewSet.

If you still want to use a router for that view, see this answer for a workaround.