DRF serialization infrastructure

Integral single change

Routing layer, a model layer, do not need to modify the sequence layer, only needs to handle the view layer: views.py

"" " 
1) a single overall change described to provide a modified data reception, then the data needs to be verified, in the verification data should be instantiated" serializing class object ", assigned to Data 
2) modified, it must be clear modified model class objects, and an instance "of the class object serialization", assigned to the instance 
. 3) integrally modifications, all validation rules have required = True field must be provided, as in the example of "sequence classes when object ", the default parameter is False partial 


NOTE: If the partial value is set to True, that can be locally changed 
1) a single overall modification, generally put request by: 
V2BookModelSerializer ( 
    instance = object to be updated, 
    the data is used to update data = , 
    partial default = False, must participate in all fields check 
) 
2) single local modification, usually with patch request: 
V2BookModelSerializer ( 
    instance = object to be updated, 
    data = data to update, 
    partial set = True, must fields become optional field 
) 
    Note: partial set True essence is to make the field required = True validation rules fail 
. "" "
class V2Book (APIView):
     # Single overall change: data v2 / books / (pk) / pass is the model name corresponding to the dictionary {|. price | publish | the authors} 
    DEF PUT (Self, Request, args *, ** kwargs): 
        request_data = request.data 
        PK = kwargs.get ( ' PK ' ) 
        old_book_obj = models.Book.objects.filter (PK = PK) .first ()
         # Objective: to check the number of data sequences to the class to deal with - let serialization deserialization role-playing class, after the verification is successful, the sequence of classes to help you put in storage 
        book_ser = serializers.V2BookModelSerializer ( instance = old_book_obj , the Data = request_data, partial = False) 
        book_ser.is_valid (raise_exception =True)
         # check passes, the update data is completed: the target to be updated, to update new data 
        book_obj = book_ser.save () 

        return the Response ({
             ' Status ' : 0,
             ' MSG ' : ' OK ' ,
             ' Results ' : serializers.V2BookModelSerializer (book_obj) .data 
        })

 

Single modify the overall local

Layer sequence: serializers.py

# Key: ListSerializer and ModelSerializer association are: 
Meta class # ModelSerializer of - list_serializer_class 
class V2BookListSerializer (ListSerializer):
     DEF Update (Self, instance, validated_data):
         # Print (instance)   # object to update their
         # Print (validated_data )   # updated object corresponding data are
         # Print (self.child)   # model serialization class services - V2BookModelSerializer
         for index, obj in the enumerate (instance): 
            self.child.update (obj, validated_data [index]) 
        return instance 
    
# original model sequence variation class 
class V2BookModelSerializer (ModelSerializer):
     classMeta:
         # ... 
        # group change, it is necessary to set custom ListSerializer, the group update method override changed 
        list_serializer_class = V2BookListSerializer
     # ...

View layer: views.py

class V2Book (APIView):
     # Single locally modified: data v2 / books / (pk) / pass, optional data fields are key 
    # Group locally modified: for V2 / Books / 
    # Request Data - [{pk: 1 , name: 123}, {PK:. 3,. price:. 7}, {PK:. 7, publish: 2}] 
    DEF Patch (Self, Request, * args, ** kwargs): 
        request_data = request.data 
        PK = kwargs. GET ( ' PK ' ) 

        # single change, data group changes are formatted into pks = [to a subject in need a primary key identifier] | request_data = [each modified data to be modified corresponding to the object] 
        IF PK and the isinstance (request_data, dict):   # single modified 
            PKS = [PK,] 
            request_data =[request_data,]
         elif  Not PK and the isinstance (request_data, List): # group modified 
            PKS = []
             for DIC in request_data:   # traversing foreground data [{pk: 1, name: 123}, {pk: 3, price: 7 }, {pk: 7, publish : 2}], take a dictionaries 
                PK = dic.pop ( ' PK ' , None)
                 IF PK: 
                    pks.append (PK) 
                the else :
                     return the Response ({
                         ' Status ' :. 1 ,
                         'MSG ' : ' data error ' , 
                    }) 
        the else :
             return the Response ({
                 ' Status ' : 1 ,
                 ' MSG ' : ' data error ' , 
            }) 

        # pks screening and request_data data 
        # 1) pks is not the corresponding data pk pk with the deleted data is removed, the data corresponding to the index bit also removes request_data 
        # 2) is converted reasonable pks OBJS 
        OBJS = [] 
        new_request_data = []
         for index, pk inthe enumerate (PKS):
             the try :
                 # PK data corresponding rational, reasonable to store objects 
                obj = models.Book.objects.get (PK = PK) 
                objs.append (obj) 
                # corresponding to the index data needs to be saved 
                new_request_data. the append (request_data [index])
             the except :
                 # key: negative tutorial - pk corresponding to incorrect data, the index data corresponding to the removed request_data 
                # index = pks.index (PK) 
                # request_data.pop (index) 
                Continue 

        book_ser serializers.V2BookModelSerializer = (= OBJS instance, Data = new_request_data, partial = True, MANY = True) 
        book_ser.is_valid (raise_exception =True)
        book_objs = book_ser.save()

        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2BookModelSerializer(book_objs, many=True).data
        })

 

Guess you like

Origin www.cnblogs.com/KrisYzy/p/11695314.html