A single change (single overall change put)
The whole idea, as with the post, the data will be serialized, after the completion of the check, do the modifications.
View layer:
def put(self, request, *args, **kwargs): request_data = request.data pk = kwargs.get('pk') old_book_obj = models.Book.objects.filter(pk=pk).first() # Purpose: to verify many of the data to the serialization class to handle, so that the serialization deserialization role-playing class, after the verification is successful, serialization to help storage bookser = serializers.V2BookModelSerializer (instance = old_book_obj, data = request_data) # object to obtain a sequence # Raise_exception = True when the check fails, the method returns immediately view the check deserialized back to the front end of error_message bookser.is_valid(raise_exception=True) New data to be updated target for the update: # check is passed, the complete update data book_obj = bookser.save() return Response({ 'status': 0, 'msg': 'ok', 'results': serializers.V2BookModelSerializer(book_obj).data })
note:
. 1 . 1 when) 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 "sequence of the class object", assigned to Data 2 2 ) modified, it must be clear modified model class objects, and an instance "of the class object serialization", assigned to the instance . 3 . 3) integrally modifications, all validation rules have = required True field, must be provided, as in the example of "sequence classes when object "parameter partial default is False . 4 . 5 . 6 Note: If the partial value is set to True, that can be locally changed . 7 . 1 :) single overall modification, usually with put request . 8 (V2BookModelSerializer . 9 instance = object to be updated, 10 data = data to update, . 11 partial = default False, must participate in all the check field 12 )
Two single local modification
Based monocytogenes, just add the partial serialization = True
def dispatch(self, request, *args, **kwargs): request_data = request.data pk = kwargs.get('pk') old_book_obj = models.Book.objects.filter (PK = PK) .first () # Purpose: To verify the number of data to serialize the class to handle, so that the serialization class plays the role of anti-serialization, validation is successful, serialization to help storage bookser = serializers.V2BookModelSerializer (= old_book_obj instance, Data = request_data, partial = True) # give a serialized object # raise_exception = True when the check fails, the method returns immediately view the check deserialize error_message returned to the front end bookser.is_valid (raise_exception = True) # after the check passes, the update data is completed: the target to be updated, to update new data book_obj = bookser.save () return the Response ({ ' Status ' : 0, ' MSG ' : 'ok', 'results': serializers.V2BookModelSerializer(book_obj).data })
note:
Single local modification, usually with patch request: V2BookModelSerializer( instance = object to be updated, Data = Data for updating, partial = setting True, the field must have become optional field ) Note: True nature of partial setting is to make the field required = True validation rules fail
Three single local modifications to the overall
Layer sequence: serializers.py
# Key: ListSerializer associated with ModelSerializer are: # ModelSerializer of Meta class - 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) # service model serialization class - V2BookModelSerializer for index, obj in enumerate(instance): self.child.update(obj, validated_data[index]) return instance # Original model serialization class changes class V2BookModelSerializer(ModelSerializer): class Meta: # ... # Group change, it is necessary to set custom ListSerializer, overwriting update method modified group of list_serializer_class = V2BookListSerializer
View layer:
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 = [objects to be the primary key identifier needs] | request_data = [modified data for each object to be changed corresponding to] IF PK and the isinstance (request_data, dict): # Single change = 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 get value take 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 with request_data data filtering, # 1) with no corresponding data is deleted data pk pk pks 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 in the 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.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) the Continue book_ser = serializers.V2BookModelSerializer(instance=objs, 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 })