mixins.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from __future__ import unicode_literals, print_function
  2. from django.core.exceptions import ValidationError
  3. from rest_framework import status
  4. from rest_framework.mixins import CreateModelMixin
  5. from rest_framework.response import Response
  6. class BulkCreateModelMixin(CreateModelMixin):
  7. """
  8. Either create a single or many model instances in bulk by using the
  9. Serializer's ``many=True`` ability from Django REST >= 2.2.5.
  10. .. note::
  11. This mixin uses the same method to create model instances
  12. as ``CreateModelMixin`` because both non-bulk and bulk
  13. requests will use ``POST`` request method.
  14. """
  15. def create(self, request, *args, **kwargs):
  16. bulk = isinstance(request.DATA, list)
  17. if not bulk:
  18. return super(BulkCreateModelMixin, self).create(request, *args, **kwargs)
  19. else:
  20. serializer = self.get_serializer(data=request.DATA, many=True)
  21. if serializer.is_valid():
  22. [self.pre_save(obj) for obj in serializer.object]
  23. self.object = serializer.save(force_insert=True)
  24. [self.post_save(obj) for obj in self.object]
  25. return Response(serializer.data, status=status.HTTP_201_CREATED)
  26. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  27. class BulkUpdateModelMixin(object):
  28. """
  29. Update model instances in bulk by using the Serializer's
  30. ``many=True`` ability from Django REST >= 2.2.5.
  31. """
  32. def bulk_update(self, request, *args, **kwargs):
  33. partial = kwargs.pop('partial', False)
  34. # restrict the update to the filtered queryset
  35. serializer = self.get_serializer(self.filter_queryset(self.get_queryset()),
  36. data=request.DATA,
  37. many=True,
  38. partial=partial)
  39. if serializer.is_valid():
  40. try:
  41. self.pre_save(serializer.object)
  42. except ValidationError as err:
  43. # full_clean on model instances may be called in pre_save
  44. # so we have to handle eventual errors.
  45. return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
  46. self.object = serializer.save(force_update=True)
  47. [self.post_save(obj, created=False) for obj in self.object]
  48. return Response(serializer.data, status=status.HTTP_200_OK)
  49. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  50. def partial_bulk_update(self, request, *args, **kwargs):
  51. kwargs['partial'] = True
  52. return self.bulk_update(request, *args, **kwargs)
  53. class BulkDestroyModelMixin(object):
  54. """
  55. Destroy model instances.
  56. """
  57. def allow_bulk_destroy(self, qs, filtered):
  58. """
  59. Hook to ensure that the bulk destroy should be allowed.
  60. By default this checks that the destroy is only applied to
  61. filtered querysets.
  62. """
  63. return qs is not filtered
  64. def bulk_destroy(self, request, *args, **kwargs):
  65. qs = self.get_queryset()
  66. filtered = self.filter_queryset(qs)
  67. if not self.allow_bulk_destroy(qs, filtered):
  68. return Response(status=status.HTTP_400_BAD_REQUEST)
  69. for obj in filtered:
  70. self.pre_delete(obj)
  71. obj.delete()
  72. self.post_delete(obj)
  73. return Response(status=status.HTTP_204_NO_CONTENT)