sportsman.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.shortcuts import get_object_or_404
  2. from rest_framework import viewsets, permissions
  3. from rest_framework.response import Response
  4. from webservice_running.models import Sportsman
  5. from webservice_running.serializers import SportsmanSerializer
  6. class SportsmanMVS(viewsets.ModelViewSet):
  7. serializer_class = SportsmanSerializer
  8. queryset = Sportsman.objects.all()
  9. #permission_classes = [IsOwnerOrReadOnly]
  10. #permission_classes = [permissions.IsAuthenticated]
  11. def get_queryset(self):
  12. """
  13. Optionally restricts the returned sportsmen to a given phone number,
  14. by filtering against a `phone_number` query parameter in the URL.
  15. """
  16. print(self.kwargs)
  17. queryset = Sportsman.objects.select_related('client__user')
  18. phone_number = self.request.query_params.get('phone_number', None)
  19. if phone_number is not None:
  20. queryset = queryset.filter(client__user__phone_number=phone_number)
  21. return queryset
  22. def get_object(self, queryset=None):
  23. """
  24. Returns the object the view is displaying.
  25. You may want to override this if you need to provide non-standard
  26. queryset lookups. Eg if objects are referenced using multiple
  27. keyword arguments in the url conf.
  28. """
  29. queryset = self.filter_queryset(self.get_queryset())
  30. # Perform the lookup filtering.
  31. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
  32. assert lookup_url_kwarg in self.kwargs, (
  33. 'Expected view %s to be called with a URL keyword argument '
  34. 'named "%s". Fix your URL conf, or set the `.lookup_field` '
  35. 'attribute on the view correctly.' %
  36. (self.__class__.__name__, lookup_url_kwarg)
  37. )
  38. filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
  39. obj = get_object_or_404(queryset, **filter_kwargs)
  40. # May raise a permission denied
  41. self.check_object_permissions(self.request, obj)
  42. return obj
  43. def update(self, request, *args, **kwargs):
  44. partial = kwargs.pop('partial', False)
  45. instance = self.get_object()# Event.objects.select_related('order_synced__ticket').get(id=1)
  46. serializer = self.get_serializer(instance, data=request.data, partial=partial)
  47. # for serializer in serializers:
  48. serializer.is_valid(raise_exception=True)
  49. self.perform_update(serializer)
  50. if getattr(instance, '_prefetched_objects_cache', None):
  51. # If 'prefetch_related' has been applied to a queryset, we need to
  52. # forcibly invalidate the prefetch cache on the instance.
  53. instance._prefetched_objects_cache = {}
  54. return Response(serializer.data)