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.

57 lines
2.2 KiB

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, Project
  10. from ..permissions import IsInProjectReadOnlyOrAdmin
  11. from ..serializers import DocumentSerializer
  12. class DocumentList(generics.ListCreateAPIView):
  13. serializer_class = DocumentSerializer
  14. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  15. search_fields = ('text',)
  16. ordering_fields = ('created_at', 'updated_at', 'doc_annotations__updated_at',
  17. 'seq_annotations__updated_at', 'seq2seq_annotations__updated_at')
  18. filter_class = DocumentFilter
  19. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  20. def get_queryset(self):
  21. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  22. queryset = project.documents
  23. if project.randomize_document_order:
  24. random.seed(self.request.user.id)
  25. value = random.randrange(2, 20)
  26. queryset = queryset.annotate(sort_id=F('id') % value).order_by('sort_id', 'id')
  27. else:
  28. queryset = queryset.order_by('id')
  29. return queryset
  30. def perform_create(self, serializer):
  31. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  32. serializer.save(project=project)
  33. def delete(self, request, *args, **kwargs):
  34. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  35. queryset = project.documents
  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 DocumentDetail(generics.RetrieveUpdateDestroyAPIView):
  43. queryset = Document.objects.all()
  44. serializer_class = DocumentSerializer
  45. lookup_url_kwarg = 'doc_id'
  46. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]