delete object through Django REST API

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

delete object through Django REST API



I'm trying to delete "Product" object using Django REST API but don't know how to do this.



serializer:


class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'product_name', 'measure', 'barcode')



I can create product using this function


def create_product(request):
data = request.POST
serializer = ProductSerializer(data=data)
if serializer.is_valid():
serializer.save()



But I don't know how to delete



There is no serializer.delete() method.





Have your view inherit from the ModelViewSet(cdrf.co/3.7/rest_framework.viewsets/ModelViewSet.html). destroy is pretty much handled there with the rest of the CRUD functionality. You can set the allowed_methods property to allow only HTTP operations that you care about.
– Oluwafemi Sule
29 mins ago



destroy


allowed_methods




2 Answers
2



You can do that using query set:


@api_view(["DELETE"])
def product_delete_rest_endpoint(request, product_id):
Product.objects.get(id=product_id).delete()
return Response()



If your view(set) inherits from DestroyModelMixin, or a viewset which inherit's from it, e.g. ModelViewSet, http DELETE is supported out of the box. You can test it with curl, for example curl -X DELETE "http://localhost:8000/your-api/products/<product-id>".


DestroyModelMixin


ModelViewSet


DELETE


curl -X DELETE "http://localhost:8000/your-api/products/<product-id>"






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

Executable numpy error

Trying to Print Gridster Items to PDF without overlapping contents

Mass disable jenkins jobs