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.1 KiB

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