From the course: Building RESTful Web APIs with Django

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Creating a DestroyAPIView subclass

Creating a DestroyAPIView subclass

From the course: Building RESTful Web APIs with Django

Start my 1-month free trial

Creating a DestroyAPIView subclass

- We can list products, and create them, but what about if we want to delete products from the database? We can use the generic view DestroyAPIView to create an API for that. We import it, and then we create our DestroyView. We set the queryset to All Products and the lookup_field to id. There isn't much to creating an API View to destroy an object. We just need to set the queryset and the lookup field. In a real world situation, however, a product being destroyed may also mean that all caches that store data related to that product have to be cleared. Clearing the cache when a model is destroyed frees up cache space for other objects that are more likely to be used. Let's see how that looks. We override the delete method, we extract the product_id from the request, we proceed with deleting the object, and if the product was deleted successfully, we're going to import the django.cache and delete the product_data from the cache. Then we just return to response, as per usual, and that's…

Contents