Browse Source

update sportsman serializer

yobafromstarvvars 1 year ago
parent
commit
7294dab870

+ 46 - 1
apiviews/sportsman.py

@@ -8,4 +8,49 @@ class SportsmanMVS(viewsets.ModelViewSet):
     queryset = Sportsman.objects.all()
     serializer_class = SportsmanSerializer
     #permission_classes = [IsOwnerOrReadOnly]
-    #permission_classes = [permissions.IsAuthenticated]
+    #permission_classes = [permissions.IsAuthenticated]
+
+    def get_object(self):
+        """
+        Returns the object the view is displaying.
+
+        You may want to override this if you need to provide non-standard
+        queryset lookups.  Eg if objects are referenced using multiple
+        keyword arguments in the url conf.
+        """
+        # queryset = self.filter_queryset(self.get_queryset())
+        queryset = Sportsman.objects.select_related('client__user')
+
+        # Perform the lookup filtering.
+        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
+
+        assert lookup_url_kwarg in self.kwargs, (
+            'Expected view %s to be called with a URL keyword argument '
+            'named "%s". Fix your URL conf, or set the `.lookup_field` '
+            'attribute on the view correctly.' %
+            (self.__class__.__name__, lookup_url_kwarg)
+        )
+
+        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
+        obj = get_object_or_404(queryset, **filter_kwargs)
+
+        # May raise a permission denied
+        self.check_object_permissions(self.request, obj)
+
+        return obj
+
+
+    def update(self, request, *args, **kwargs):
+        partial = kwargs.pop('partial', False)
+        instance = self.get_object()# Event.objects.select_related('order_synced__ticket').get(id=1)
+        serializer = self.get_serializer(instance, data=request.data, partial=partial)
+        # for serializer in serializers:
+        serializer.is_valid(raise_exception=True)
+        self.perform_update(serializer)
+
+        if getattr(instance, '_prefetched_objects_cache', None):
+            # If 'prefetch_related' has been applied to a queryset, we need to
+            # forcibly invalidate the prefetch cache on the instance.
+            instance._prefetched_objects_cache = {}
+
+        return Response(serializer.data)

+ 2 - 1
exceptions/__init__.py

@@ -1 +1,2 @@
-from .order_not_defined import OrderNotDefined
+from .order_not_defined import OrderNotDefined
+from .client_not_defined import ClientNotDefined

+ 7 - 0
exceptions/client_not_defined.py

@@ -0,0 +1,7 @@
+class ClientNotDefined(Exception):
+    """
+    If order_synced field is not defined throw exception
+    """
+    def __init__(self, message="client field is not defined"):
+        self.message = message
+        super().__init__(self.message)

+ 0 - 0
possible_api_requests.txt


+ 79 - 1
serializers/sportsman.py

@@ -1,8 +1,86 @@
 from rest_framework import serializers
 from webservice_running.models import Sportsman
+from metaservicesynced.models import Client
+from SharixAdmin.models import SharixUser
+from webservice_running.exceptions import ClientNotDefined
+from rest_framework.response import Response
 
 
 class SportsmanSerializer(serializers.ModelSerializer):
     class Meta:
         model = Sportsman
-        exclude = ["id"]
+        exclude = ["blocked_sportsman", 
+                   "browse_sportsman",
+                    "saved_sportsman",
+                    "sport_preferrence",
+                    "achievement",
+                    "saved_event",
+                    "participant",
+                    "browse_event",]
+
+    # User data
+    phone_number = serializers.CharField(source="client.user.phone_number")
+    first_name = serializers.CharField(source="client.user.first_name")
+    last_name = serializers.CharField(source="client.user.last_name")
+    email = serializers.CharField(source="client.user.email")
+    # Client data
+    requirements = serializers.CharField(source="client.user.requirements")
+    status = serializers.CharField(source="client.user.status")
+    ticket_status = serializers.IntegerField(source="client.ticket_status.pk")
+    id_metaservice = serializers.IntegerField(source="client.id_metaservice")
+    is_global = serializers.BooleanField(source="client.is_global")
+    is_visible = serializers.BooleanField(source="client.is_visible")
+
+
+    # def create(self, validated_data):
+    #     print("="*30)
+    #     print(validated_data['client'].status)
+    #     # # Temporary solution
+    #     # client_fields = ("requirements", "status", "ticket_status", "id_metaservice", "is_global", "is_visible")
+    #     # for attr, value in validated_data.items():
+    #     #     # If "client" in req, then User model is accessed
+    #     #     if attr == "client":
+    #     #         for u_attr, u_value in value.get('user').items():
+    #     #             setattr(user_instance, u_attr, u_value)
+    #     #     else:
+    #     #         setattr(instance, attr, value)
+
+    #     # for i in validated_data.items():
+    #     #     pass
+    #     # user_instance = SharixUser._default_manager.create(**validated_data)
+    #     # client_instance = Client._default_manager.create(**validated_data)
+    #     # instance = Sportsman._default_manager.create(**validated_data)
+    #     # return instance
+        
+
+    def update(self, instance, validated_data):
+        client_instance = instance.client
+        if not client_instance:
+            raise ClientNotDefined()
+        user_instance = instance.client.user
+
+        for attr, value in validated_data.items():
+            # If "client" in req, then User model is accessed
+            if attr == "client":
+                for u_attr, u_value in value.get('user').items():
+                    setattr(user_instance, u_attr, u_value)
+            else:
+                setattr(instance, attr, value)
+
+        instance.save()
+        user_instance.save()
+        
+        return instance
+
+'''
+
+{
+    'client': {
+        'user': {
+            'phone_number': '99999999999', 
+            'email': 'email'
+        }
+    },
+    'bio': 'bio test'}
+
+'''

+ 1 - 1
urls.py

@@ -22,6 +22,6 @@ router.register(r'sport', SportMVS)
 router.register(r'sportsman_gallery', SportsmanGalleryMVS)
 
 urlpatterns = [
-    path("", views.order_reg, name="order_reg"),
+    # path("", views.order_reg, name="order_reg"),
     re_path(r'^api/', include(router.urls), name="webservice_running_api"),
 ]

+ 1 - 1
views/__init__.py

@@ -1 +1 @@
-from .views import order_reg
+from . import order_reg

+ 3 - 3
views/views.py → views/order_reg.py

@@ -3,7 +3,7 @@ from webservice_running.forms import OrderRegForm
 
 def order_reg(request):
     if request.method == 'POST':
-      form = OrderRegForm(request.POST)
-      if form.is_valid():
-          form.save()
+        form = OrderRegForm(request.POST)
+        if form.is_valid():
+            form.save()
     return render(request, 'webservice/order_reg.html', {'form': form})