-1

i want to build a ModelViewSet class that recive an id from url for instance

localhost/id

and based on that id i can either show the object with matching id or delete the object but im having trouble passing the id in the url my view is like this:

class delete_or_show_View(viewsets.ModelViewSet):
    serializer_class = ObjectSerializer
    permission_classes = [permissions.IsAuthenticated]
    http_method_names = ['get', 'delete']

    def get_queryset(self,mid):
        #Show the object


    def destroy(self, mid):
        #delete the object

and my url is like this

router.register('(?P<object_id>\d+)', views.delete_or_show_View, basename='do_stuff')

Im getting errors for missing aruguments or that the delete method is not allowed please if someone can guide me how i can do this properly and explain it will be great thank you

Lin
  • 13
  • 2

1 Answers1

2
class DeleteOrShowView(viewsets.ModelViewSet):
    serializer_class = ObjectSerializer
    permission_classes = [permissions.IsAuthenticated]
    queryset = Model.objects.all()
    http_method_names = ['get', 'delete']

then update your urls.py as

router = DefaultRouter()
router.register('show-delete', views.DeleteOrShowView, basename='do_stuff')

now you can just pass along with this url when hitting this api show-delete/<id>/

Sarath R
  • 156
  • 6
  • how it gets the id from the url? because ve tried what you suggested and im getting 404 like there is no path either for get or delete requests – Lin Nov 26 '22 at 17:14
  • Sorry, you can remove the slash in that URL. just use `router.register('show-delete', views.DeleteOrShowView, basename='do_stuff')` I have updated the same in the answer. router follows this format and has id as default look up field when we pass some values after the url followed by a slash. – Sarath R Nov 26 '22 at 17:18
  • thank you it works, BTW if i want to return a Response that the message has been deleted i need to do write my own destroy function? – Lin Nov 26 '22 at 17:25
  • you can customize the `def destroy(self, request, *args, **kwargs)` function to add custom messages – Sarath R Nov 26 '22 at 17:29
  • and for the show, i can do the same with `def get_queryset(self)` or `def get_object(self)`? – Lin Nov 26 '22 at 17:54
  • if you need to update the queryset with some filters, then you can customize `get_queryset`. But in case of getting single object, you do not need to update `get_object`, just passing the ID in URL is enough. – Sarath R Nov 26 '22 at 17:58
  • final question if i want to update in the show function i need to use `get_queryset` but how i can get the id i passed? – Lin Nov 26 '22 at 18:05
  • you can use `self.get_object().id` inside the `get_queryset` function to get the object id – Sarath R Nov 26 '22 at 18:53