How to delete single and multiple objects in Django / DRF

This post is related to or in continuation with our previous post “Writing class based Views in Django REST Framework” where we had implemented “get”, “post” and “put” methods , in this post we will show you how you can delete the single object from the JSON or multiple objects with same “username” from the json object.

We need to modify the views.py class to add one more “delete” method. In this function, we need to first get the respective object which we want to delete, and this can be done using following code,

user = UserInfo.objects.get(username=user_name)

here, UserInfo is the model, for your implementation it can be any name as you use in your models.py.

Once we got the respective object to delete, we just need to call delete() on the same object as,

if user:
    user.delete()

Hence the complete code to delete single object can be written in views.py as,

    def delete(self, request, user_name, format=None):
        user = UserInfo.objects.get(username=user_name)
        if user:
            user.delete()
            return JsonResponse({"status":"ok"}, status=status.HTTP_200_OK)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

If you have mode than one object with similar json element, in our example, same username, then we can delete these multiple objects by using filters. Multiple objects can be deleted using “filter” as,

    def delete(self, request, user_name, format=None):
        users = UserInfo.objects.filter(username=user_name)
        if users:
            users.delete()
            return JsonResponse({"status":"ok"}, status=status.HTTP_200_OK)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

As you can see, “filter” return multiple objects, so even if you have only one object, it will return the same and using “filter” you can also delete single object as well.

Hence you can use filter to delete single as well as multiple objects.

Deleting all the objects of particular model can be done as,

def delete(self, request, format=None):
        users = UserInfo.objects.all()
        if users:
            users.delete()
            return JsonResponse({"status":"ok"}, status=status.HTTP_200_OK)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Leave a Comment