1

i'm trying to use django generic view. and i want to be able to delete multiple objects at the same time using the same view.for example delete all the 'femail' Employees in my model. i used the following code:

from ..models import Employee
from . import serializer
from rest_framework import generics, status
from rest_framework.response import Response
from django.shortcuts import get_list_or_404, get_object_or_404

class EmployeeDeleteandUpdate(generics.UpdateAPIView):
    queryset = Employee.objects.filter(gender__startswith='femail')
    serializer_class = serializer.PostSerializer

    def delete(self, request, *args, **kwargs):
        myobj = get_object_or_404(Employee, gender=kwargs['gender'])
        myobj.delete()
        return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT)

and heres my url code:

path('mydel/<str:gender>/', view.EmployeeDeleteandUpdate.as_view()),

and also my model:

class Employee(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    gender = models.CharField(max_length=10)
    national_code = models.CharField(max_length=11)
    personal_code = models.CharField(max_length=15)
    phone_number = models.CharField(max_length=11)
    address = models.CharField(max_length=50)
    married = models.BooleanField()
    age = models.IntegerField()
    wage = models.IntegerField()

     def __str__(self):
         return self.first_name

but when i use delete method with following url in my django rest framework:

http://127.0.0.1:8000/mydel/femail/

i get this error:

client.models.Employee.MultipleObjectsReturned: get() returned more than one Employee -- it returned 2!

can somebody help me with this problem please??

1 Answer 1

1

The get_object_or_404 method only gets 1 object from the table so it is compulsory the record will be unique in the table. Otherwise, it gives an error.

Please try this code:

  def delete(self, request, *args, **kwargs):
        employees = Employee.objects.filter(gender=kwargs['gender'])
        if employees.count() > 0:
           employees.delete()
           return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT)
        return Response("Unable to find the femails.", status=status.HTTP_404_OK)

In this code snippet, I am filtering the result based on kwargs['gender'] and then count its objects if greater than one then delete it using the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.