4

I am trying to implement a RESTful web service. Everything was going well until I tried to deserialize a list with objects from a post request. My code is this:

#serializers.py
class ResultSerializer(serializers.ModelSerializer):
        class Meta:
            model=test_result
            fields=('id', 'label')

#views.py
class results(APIView):
    """
    Post the results for a test set.
    """
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, pk, format=None):
        ser=ResultSerializer(data=request.DATA)
        for i in range(len(ser.data)): 
            if ser.data[i].is_valid():      
            entry=test_result(user=User.objects.get(username=request.user.username), test_id=Detail.objects.get(test_id=pk), id=Article.objects.get(id=ser.data[i]['id']), label=ser.data[i]['label'])
            entry.save() #I use a test_result table in my database to save things   
            return Response(ser.data[i], status=status.HTTP_201_CREATED)    
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)

The curl command i use to test is:

curl -v -H "Accept: application/json" -H "Content-type: application/json" --user plao:1234 -X POST -d '[{"id":23401853, "label":1504}, {"id":23401853, "label":1505}]' http://127.0.0.1:8000/tests/uploadResults/1/

I have tested my code (without the indexes) with simple post and it works fine. But when I try to post a list I can't. However, after trying the code in the shell (python manage.py shell) I noticed that there is a TODO in the code of the framework:

# TODO: error data when deserializing lists

Is there a problem with the code? Is there any advise I can use? In the final version the users will post strings like the following one, but I try to reach it step by step:

{"documents": [{"id":[Label1,...,LabelN]},....,{"id":[Label1,..,LabelM]}]}

If I can handle lists I will be able to hanble that kind of json.

4

1 回答 1

1

您可能应该看看讨论组上的这个线程,它处理批量更新:

https://groups.google.com/forum/#!topic/django-rest-framework/uJA1kuUO9gc/discussion

于 2013-02-19T13:32:25.007 回答