如何在django rest框架中复制请求

时间:2015-11-25 22:20:39

标签: django django-rest-framework

假设我有这段代码

if (!empty($_POST['price'])) {

switch ($_POST['price']) {
        case 1: 
            $where = " WHERE price BETWEEN 0.00 AND 1.00";
            break;
        case 2: 
            $where = " WHERE price BETWEEN 1.00 AND 5.00";
            break;
        case 3: 
            $where = " WHERE price BETWEEN 5.00 AND 10.00";
            break;
        default:
            break;
    }
}

现在让我们假设在我的获取中,我需要修改request.data

class SnippetList(APIView):
    """
    List all snippets, or create a new snippet.
    """
    def get(self, request, format=None):
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

有没有办法做到这一点

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

def get(self, request, format=None):
        response = self.post(self, request, format=None, data=data )  # i want to do post method now with new request
        serializer = SnippetSerializer(snippets, many=True)

现在你的方法帖子应该是:

def post(self, request, format=None, **kwargs):
        original_data = request.data
        additional_data = kwargs.get('data') # now you will be able to do whatever you want
        # more code goes here

答案 1 :(得分:0)

您不应该在get时修改数据,因为它们通常被标记为“不安全”,因为它们会修改数据状态。

您也不想弄乱提供的请求。它经常会产生比解决更多的问题并增加一些魔力。

如果您希望序列化程序拥有的数据多于发送的请求数据,则应将它们传递给序列化程序的保存功能。它们将被添加到validated_data中,并在序列化程序的创建/更新方法中可用(http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save