6
0

sportsman.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. queryset = Sportsman.objects.select_related('client__user')
  17. phone_number = self.request.query_params.get('phone_number', None)
  18. if phone_number is not None:
  19. queryset = queryset.filter(client__user__phone_number=phone_number)
  20. return queryset
  21. def get_object(self, queryset=None):
  22. """
  23. Returns the object the view is displaying.
  24. You may want to override this if you need to provide non-standard
  25. queryset lookups. Eg if objects are referenced using multiple
  26. keyword arguments in the url conf.
  27. """
  28. queryset = self.filter_queryset(self.get_queryset())
  29. # Perform the lookup filtering.
  30. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
  31. assert lookup_url_kwarg in self.kwargs, (
  32. 'Expected view %s to be called with a URL keyword argument '
  33. 'named "%s". Fix your URL conf, or set the `.lookup_field` '
  34. 'attribute on the view correctly.' %
  35. (self.__class__.__name__, lookup_url_kwarg)
  36. )
  37. filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
  38. obj = get_object_or_404(queryset, **filter_kwargs)
  39. # May raise a permission denied
  40. self.check_object_permissions(self.request, obj)
  41. return obj
  42. def update(self, request, *args, **kwargs):
  43. partial = kwargs.pop('partial', False)
  44. instance = self.get_object()# Event.objects.select_related('order_synced__ticket').get(id=1)
  45. serializer = self.get_serializer(instance, data=request.data, partial=partial)
  46. # for serializer in serializers:
  47. serializer.is_valid(raise_exception=True)
  48. self.perform_update(serializer)
  49. if getattr(instance, '_prefetched_objects_cache', None):
  50. # If 'prefetch_related' has been applied to a queryset, we need to
  51. # forcibly invalidate the prefetch cache on the instance.
  52. instance._prefetched_objects_cache = {}
  53. return Response(serializer.data)