django无法在帖子上序列化非模型

时间:2013-07-17 15:22:21

标签: python django django-rest-framework

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)

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您需要在访问数据之前访问'serializer.is_valid()'。看起来那里缺少一些API - 如果在验证之前访问它,serializer.data应该提出一个预期。

答案 1 :(得分:0)

似乎您没有使用Django's serializers,但无论如何都不进行序列化以进行验证。使用forms验证您的数据,然后使用json进行序列化。 Django的序列化器仅用于查询集和模型。