-1

I have the following Viewset:

class My_ViewSet(viewsets.ModelViewSet):
    serializer_class = My_Serializer
    queryset = My_Object.objects.all()

    def list(self, request):
        # The code here is irrelevant
        return Response()

    def retrieve(self, request, pk=None):
        # The code here is irrelevant
        my_object = get_object_or_404(My_Object, id=pk)
        return Response(my_object.id)

urls.py sample:

urlpatterns = [
    path('api/my_object/', My_ViewSet.as_view({'get': 'list'})),
    path('api/my_object/<int:pk>/', My_ViewSet.as_view({'get': 'retrieve'})),
]

When I try to make OPTIONS request on api/my_object/ I have the following error:

AssertionError: Expected view My_ViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

SWater
  • 384
  • 1
  • 13

1 Answers1

-1

This is because you've defined the retrieve method in your My_ViewSet to expect a pk argument, which is used to retrieve a single object from your queryset. However, in your urls.py file, you haven't specified the pk argument in the URL pattern for the list method.

urls.py

urlpatterns = [
    path('api/my_object/', My_ViewSet.as_view({'get': 'list'})),
    path('api/my_object/<int:pk>/', My_ViewSet.as_view({'get': 'retrieve'})),
]
Blind2k
  • 350
  • 3
  • 13
  • my urls.py are exactly the same as in your "answer" and I am not making a GET request, but OPTIONS request – SWater Apr 11 '23 at 10:49