Django Restful Framework更新对象

时间:2017-10-24 22:37:52

标签: python django django-rest-framework

我是Django Restful Framework的初学者。我想创建一个BookAPI,这是我的模型:

models.py

book_id = models.AutoField(primary_key=True)
book_name = models.CharField(max_length=64, null=False)
order = models.IntegerField(null=True)

现在我可以获得没有订单的书籍清单    获得http://localhost:8000/api/books/

我想修改图书的顺序,让每本书都有一个PUT http://localhost:8000/api/books/orders

的独特订单
"Payload":
{
"books": [
    {
        "book_id": 1,
        "order": 1
    },
    {
        "book_id": 2,
        "order": 2
    }
]

}

和回复:

"Response":
[
{
    "book_id": 1,
    "order": 1
},
{
    "book_id": 2,
    "order": 2
}
]

这是我的serializer.py:

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Book
        fields=['book_id','order']

我应该如何处理serializer.py中的更新功能?

这是我的view.py

class OrderAPIView(APIView):
    #get order and book id
    serializer_class = OrderSerializer
    permission_classes = [AllowAny]
    def post(self, request, book_id):
        order = order.objects.get(book_id=book_id)
        serializer = OrderSerializer(order, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您对如何指定图书订单的计划是什么?它应该是PUT上的PATCH还是/api/books/<book_id>?另外,你能展示你的观点吗?