[Fixed]-POST json array and get response as json array

1👍

use this:

class RoFileSerializer(serializers.ModelSerializer):

    class Meta:
        model = RoFile
        fields = '__all__'
        read_only_fields = ('deleted', 'user', 'info')

class RoFileListCreateApi(generics.ListCreateAPIView):
    serializer_class = RoFileSerializer

    def get_queryset(self):
         return Rofile.objects.filter(md5check=self.request.data['md5check'])

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        # override perform_create or the serializers create method for custom create logic
        self.perform_create(serializer)
        # assign other fields to the objs and save again
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

You just have to pass many=True to the serializer for handling lists.

Override perform_create method in the generic view or the serializers create method for applying custom creation logic.

EDIT:

based on new info provided I have changed the create method.

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data, many=True)
    serializer.is_valid(raise_exception=True)
    # don't create anything just insert required data
    for rof_data in serializer.data:
        md5check = rof_data['md5check']
        # code to retrieve data from db based on md5check
        ....
        # code to insert values in rof_data
        rof_data['user'] = user.username
        rof_data['deleted'] = deleted
        rof_data['info'] = info
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Leave a comment