mixins.py 3.6 KB

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