Ver Fonte

updated views and serializer: added partial update

yobafromstarvvars há 1 ano atrás
pai
commit
37efbf91a2
5 ficheiros alterados com 104 adições e 53 exclusões
  1. 3 1
      admin.py
  2. 55 49
      apiviews/orders_local.py
  3. 10 0
      factory.py
  4. 35 2
      serializer/orders_local.py
  5. 1 1
      urls.py

+ 3 - 1
admin.py

@@ -1,3 +1,5 @@
 from django.contrib import admin
+from openlocal.models import OrdersLocal
 
-# Register your models here.
+
+admin.site.register(OrdersLocal)

+ 55 - 49
apiviews/orders_local.py

@@ -1,63 +1,69 @@
 from django.http import Http404, HttpResponse
+from django.shortcuts import get_object_or_404
 from openlocal.serializer import OrdersLocalSerializer
 from rest_framework import viewsets, permissions, status
 from rest_framework.response import Response
 from rest_framework.exceptions import NotFound
 from openlocal.models import OrdersLocal
-from metaservicesynced.models import Orders, Service, ServiceType, Provider, Client
-from SharixAdmin.models import SharixUser
-from tickets.models import Task
+# from metaservicesynced.models import Orders, Service, ServiceType, Provider, Client
+# from SharixAdmin.models import SharixUser
+# from tickets.models import Task
+# from tickets.serializer import TaskSerializer
 
 class OrdersLocalMVS(viewsets.ModelViewSet):
-
     queryset = OrdersLocal.objects.all()
     serializer_class = OrdersLocalSerializer
     #permission_classes = [IsOwnerOrReadOnly]
     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 = OrdersLocal.objects.select_related('order_synced__ticket')
+
+        # 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):
-        if request.data['order_synced']:
-            order = Orders.objects.get(pk=int(request.data['order_synced']))        
-            try:
-                #Подумать над этим
-                if request.data['is_global'] == True:
-                    order.is_global = True
-                elif request.data['is_gloabl'] == False:
-                    order.is_global = False
-                if request.data['is_visible'] == True:
-                    order.is_visible = True
-                elif request.data['is_visible'] == False:
-                    order.is_visible = False
-                order.service = Service.objects.get(pk=request.data['service'])
-                order.service_type = ServiceType.objects.get(pk=request.data['service_type'])
-                order.provider = Provider.objects.get(pk=request.data['provider'])
-                order.receiver = SharixUser.objects.get(pk=request.data['receiver'])
-                order.client_id = Client.objects.get(pk=request.data['client_id'])
-                
-            except Exception as ex:
-                print(ex)
-                #raise NotFound(str(ex))
-            
-            order.id_metaservice = request.data['id_metaservice'] or order.id_metaservice
-            order.state = request.data['state'] or order.state
-            order.time_placed = request.data['time_placed'] or order.time_placed
-            order.time_start = request.data['time_start'] or order.time_start
-            order.time_start_real = request.data['time_start_real'] or order.time_start_real
-            order.time_start_predicted = request.data['time_start_predicted'] or order.time_start_predicted
-            order.time_finish_predicted = request.data['time_finish_predicted'] or order.time_finish_predicted
-            order.time_finish_real = request.data['time_finish_real'] or order.time_finish_real
-            order.predicted_price = request.data['predicted_price'] or order.predicted_price
-            order.real_price = request.data['real_price'] or order.real_price
-            
-            order.save()
-        if request.data['ticket']:
-            ticket = Task.objects.get(pk=request.data['ticket'])
-            ticket.status = request.data['status'] or ticket.status
-            ticket.priority = request.data['priority'] or ticket.priority
-            ticket.title = request.data['title'] or ticket.title
-            ticket.note = request.data['note'] or ticket.note
-            ticket.due_date = request.data['due_date'] or ticket.due_date
-            ticket.status_changed_date = request.data['status_changed_date'] or ticket.status_changed_date
-            ticket.save()
-        return super().update(request, *args, **kwargs)
+        partial = kwargs.pop('partial', False)
+        instance = OrdersLocal.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)
+
+    
+    
+    
+    
+    

+ 10 - 0
factory.py

@@ -0,0 +1,10 @@
+import factory
+from factory.faker import faker
+from openlocal.models import *
+from metaservicesynced.models import *
+
+class OrdersLocalFactory(factory.django.DjangoModelFactory):
+    class Meta:
+        model = OrdersLocal
+
+    

+ 35 - 2
serializer/orders_local.py

@@ -1,5 +1,13 @@
 from rest_framework import serializers
 from openlocal.models import OrdersLocal
+from tickets.models import *
+from metaservicesynced.models import Orders
+from SharixAdmin.models import SharixUser
+from tickets.serializer import TaskSerializer
+# from metaservicesynced.serializer import OrdersSerializer
+from rest_framework.utils import model_meta
+import pprint
+from django.db import connection
 
 class OrdersLocalSerializer(serializers.ModelSerializer):
     service = serializers.IntegerField(source="order_synced.service", allow_null=True)    
@@ -35,8 +43,33 @@ class OrdersLocalSerializer(serializers.ModelSerializer):
     note = serializers.CharField(source="order_synced.ticket.note", allow_null=True)
     due_date = serializers.DateField(source="order_synced.ticket.due_date", allow_null=True)
     status_changed_date = serializers.DateTimeField(source="order_synced.ticket.status_changed_date", allow_null=True)
+    # order_synced = OrdersSerializer(read_only=True)
     
-
     class Meta:
         model = OrdersLocal
-        fields = '__all__'
+        fields = "__all__"
+        # fields = ["order", "order_synced"]
+        # depth = 2
+
+
+    def update(self, instance, validated_data):
+        # pprint.pprint(connection.queries)
+        order_instance = instance.order_synced
+        ticket_instance = instance.order_synced.ticket
+        
+        for attr, value in validated_data.items():
+            if attr == "order_synced":
+                for order_synced_attr, order_synced_value in value.items():
+                    if order_synced_attr == "ticket":
+                        for ticket_attr, ticket_value in order_synced_value.items():
+                            setattr(ticket_instance, ticket_attr, ticket_value)
+                            continue
+                    else:
+                        setattr(order_instance, order_synced_attr, order_synced_value)
+            else:
+                setattr(instance, attr, value)
+
+        instance.save()
+        ticket_instance.save()
+        order_instance.save()
+        return instance

+ 1 - 1
urls.py

@@ -1,6 +1,6 @@
 from openlocal.apiviews import *
 from rest_framework import routers
-from django.urls import path, include
+from django.urls import path, include, re_path
 
 router = routers.DefaultRouter()
 router.register(r'orderslocal', OrdersLocalMVS)