Skip to content
thesarfo

Note

Deleting Objects via a View

Adding a DELETE branch to a detail view function.

views 0

To delete an object, it has to be performed in the view function that gets a single object. In this scenario, we will perform the deletion in the product_detail view function. We need to specify the DELETE method. And then we need an elif method that if the method equals delete, we delete the product and return a non existent resource. see below.

@api_view(['GET', 'PUT', 'DELETE'])
def product_detail(request, id):
product = get_object_or_404(Product, pk=id)
if request.method == 'GET':
serializer = ProductSerializer(product)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = ProductSerializer(product, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
elif request.method == 'DELETE':
product.delete()
return Response(status.status.HTTP_204_NO_CONTENT)