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.

58 lines
2.0 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 members.permissions import IsInProjectReadOnlyOrAdmin
  9. from ..filters import ExampleFilter
  10. from ..models import Example, Project
  11. from ..serializers import ExampleSerializer
  12. class ExampleList(generics.ListCreateAPIView):
  13. serializer_class = ExampleSerializer
  14. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  15. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  16. ordering_fields = ('created_at', 'updated_at')
  17. search_fields = ('text', 'filename')
  18. model = Example
  19. filter_class = ExampleFilter
  20. @property
  21. def project(self):
  22. return get_object_or_404(Project, pk=self.kwargs['project_id'])
  23. def get_queryset(self):
  24. queryset = self.model.objects.filter(project=self.project)
  25. if self.project.random_order:
  26. # Todo: fix the algorithm.
  27. random.seed(self.request.user.id)
  28. value = random.randrange(2, 20)
  29. queryset = queryset.annotate(sort_id=F('id') % value).order_by('sort_id', 'id')
  30. else:
  31. queryset = queryset.order_by('created_at')
  32. return queryset
  33. def perform_create(self, serializer):
  34. serializer.save(project=self.project)
  35. def delete(self, request, *args, **kwargs):
  36. queryset = self.project.examples
  37. delete_ids = request.data['ids']
  38. if delete_ids:
  39. queryset.filter(pk__in=delete_ids).delete()
  40. else:
  41. queryset.all().delete()
  42. return Response(status=status.HTTP_204_NO_CONTENT)
  43. class ExampleDetail(generics.RetrieveUpdateDestroyAPIView):
  44. queryset = Example.objects.all()
  45. serializer_class = ExampleSerializer
  46. lookup_url_kwarg = 'example_id'
  47. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]