You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.6 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. import random
  2. from django.db.models import F
  3. from django.shortcuts import get_object_or_404
  4. from django_filters.rest_framework import DjangoFilterBackend
  5. from rest_framework import filters, generics, status
  6. from rest_framework.permissions import IsAuthenticated
  7. from rest_framework.response import Response
  8. from ..filters import DocumentFilter
  9. from ..models import Document, Example, Image, Project
  10. from ..permissions import IsInProjectReadOnlyOrAdmin
  11. from ..serializers import (DocumentSerializer, ExampleSerializer,
  12. ImageSerializer)
  13. class ExampleList(generics.ListCreateAPIView):
  14. serializer_class = ExampleSerializer
  15. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  16. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  17. ordering_fields = ('created_at', 'updated_at')
  18. model = Example
  19. @property
  20. def project(self):
  21. return get_object_or_404(Project, pk=self.kwargs['project_id'])
  22. def get_queryset(self):
  23. queryset = self.model.objects.filter(project=self.project)
  24. if self.project.random_order:
  25. # Todo: fix the algorithm.
  26. random.seed(self.request.user.id)
  27. value = random.randrange(2, 20)
  28. queryset = queryset.annotate(sort_id=F('id') % value).order_by('sort_id', 'id')
  29. else:
  30. queryset = queryset.order_by('id')
  31. return queryset
  32. def perform_create(self, serializer):
  33. serializer.save(project=self.project)
  34. def delete(self, request, *args, **kwargs):
  35. queryset = self.project.examples
  36. delete_ids = request.data['ids']
  37. if delete_ids:
  38. queryset.filter(pk__in=delete_ids).delete()
  39. else:
  40. queryset.all().delete()
  41. return Response(status=status.HTTP_204_NO_CONTENT)
  42. class DocumentList(ExampleList):
  43. serializer_class = DocumentSerializer
  44. search_fields = ('text',)
  45. filter_class = DocumentFilter
  46. model = Document
  47. class ImageList(ExampleList):
  48. serializer_class = ImageSerializer
  49. search_fields = ('filename',)
  50. model = Image
  51. class DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
  52. queryset = Document.objects.all()
  53. serializer_class = DocumentSerializer
  54. lookup_url_kwarg = 'doc_id'
  55. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  56. class ImageDetail(generics.RetrieveUpdateDestroyAPIView):
  57. queryset = Image.objects.all()
  58. serializer_class = ImageSerializer
  59. lookup_url_kwarg = 'image_id'
  60. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]