Nik Matue
Nik Matue

Reputation: 105

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.

Upvotes: 5

Views: 9913

Answers (3)

Mahyar Majidi
Mahyar Majidi

Reputation: 91

First of all you should know how work with Router and ModelViewSet and GenericViewSet class from django rest_framework and instead of Product app let assume that you have Customer app. you should inheritance your class viewset from viewsets.ModelViewSet or viewsets.GenericViewSet and mixins.DestroyModelMixin in views.py like blow

class CustomerViewSet(viewsets.GenericViewSet, mixins.DestroyModelMixin):

or

class CustomerViewSet(viewsets.ModelViewSet):

and define serilaizer class for that viewset like this

class CustomerViewSet(viewsets.GenericViewSet, mixins.DestroyModelMixin):
      serilaizer_class = CustomerSerializer

then you should define router for all request to api in your appName folder and you should create urls.py file in that folder like below

you can see customer app folder in my project and urls.py

in urls.py define router and url patterns like this

app_name variable define the name of url used by revers function

go to the urls.py in app folder (app/urls.py) and define path like below "you should define a path to refer to customer/urls.py .. we create customer/urls.py in previous step"

Define path in (app/urls.py)

OK .. run your project in browser and type your localhost address http://(your localhost address)/api/customer/customers/1/ with DELETE request ( NOT POST, GET or PATCH request)

here is some link about router and viewset

Router : https://www.django-rest-framework.org/api-guide/routers/

ModelViewSet: https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset

Generic Viewset: https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset

Upvotes: 1

Dušan Maďar
Dušan Maďar

Reputation: 9919

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>".

Upvotes: 1

dorintufar
dorintufar

Reputation: 650

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()

Upvotes: 4

Related Questions