RESTful批量删除的返回值

时间:2015-09-16 17:25:17

标签: rest django-rest-framework

我有一个API,其模型需要能够一次删除多个模型。因此,我在List上为该模型编写了一个DELETE方法。但是,用户可能无权删除某些模型。是否有模式表明哪些模型已成功删除,哪些模型未被删除?我目前的做法是:

class ModelList(APIView):

    def delete(self, request, format=None):

        models = MyModel.objects.all()

        models.filter(<some filtering>)

        response = []
        for m in models:

            if m.deletionForbidden:
                response.append("Forbidden")
            else:
                m.delete()
                response.append("No Content")

        return Response(response)

但这感觉有些混乱/不直观。还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以在回复中返回2个密钥'deleted''forbidden'

'deleted'键包含已删除的对象ID,'forbidden'键包含用户无权删除的对象ID。

class ModelList(APIView):

    def delete(self, request, format=None):
        """
        This method performs bulk delete on objects for which a user has permission
        to delete. The response will contain 2 keys 'deleted' and 'forbidden'. These 
        will contain the ids deleted and the ids forbidden to delete.
        """        
        objs = MyModel.objects.filter(**filter_params) # list of objects to be deleted        
        ids_deleted = [] # contain the ids which are deleted
        ids_forbidden = [] # contain the ids which a user does not have permission to delete

        for obj in objs:
            if obj.deletionForbidden: # check if user has permission to delete the object
                ids_forbidden.append(obj.id) # append the id to the list              
            else:
                ids_deleted.append(obj.id) # append the id to list

        MyModel.objects.filter(id__in=ids_deleted).delete() # bulk delete all the objects

        return_dict = {
            'deleted': ids_deleted,
            'forbidden': ids_forbidden
        }

        return Response(return_dict, status=status.HTTP_204_NO_CONTENT)