0

django 新手并尝试将 id 列表发送到服务器以更新一些信息。我不希望他们成为模范班,没有必要。我要做的是将它们放入序列化程序中以确保它们是“干净的”。这是我的代码:

查看类:

class Update_Cards(APIView):
    # This seems necessary or it will throw an error
    queryset = Card.objects.all()
    def post(self, request, board_id, format=None):
        print request.DATA
        serializer = CardMoveSerializer(data=request.DATA, many=True)
        #this throws an error
        print serializer.data

        return Response(serializer.data)

序列化器:

class CardMoveSerializer(serializers.Serializer):
    card_id = serializers.IntegerField()
    lane_id = serializers.IntegerField()

我得到的错误:

[{u'lane_id': 21, u'card_id': 3}] #this is to show the data is coming across the wire
Internal Server Error: /api/board/2/updateCards
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 327, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 324, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/crob/Documents/workspace/tlckanban/python/rest/views.py", line 37, in post
    print card_moves.data
  File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 499, in data
    self._data = [self.to_native(item) for item in obj]
TypeError: 'NoneType' object is not iterable

我现在所做的是用一个 simplejson 解析器实现这个,但我觉得它不是最好的方法:

def update_cards(request, board_id):
    json_data = simplejson.loads(request.body)

    for moveIndex in range(0, len(json_data)):
        #do some work


    return JSONResponse(json_data, status=status.HTTP_200_OK)

我在这里先向您的帮助表示感谢!

4

2 回答 2

1

您需要在访问数据之前访问“serializer.is_valid()”。看起来那里缺少一些 API - 如果在验证之前访问它,serializer.data 应该可能会引起期望。

于 2013-07-17T20:12:11.163 回答
0

似乎您没有使用Django 的序列化程序,但无论如何序列化不是为了验证。使用表单来验证您的数据,然后json像您一样使用它来序列化它。Django 的序列化器仅用于查询集和模型。

于 2013-07-17T18:26:57.673 回答