0

我需要将request.POST参数移动到request.query_params QueryDict.

有没有一种公认的方式来做到这一点?

背景

我正在使用带有 DRF 后端的数据表,它工作正常。我正在将应用程序移至集成,然后......它停止工作。为什么?请求 URL 太大(在 7000 个字符范围内) - 这在我的开发主机中不是问题......

所以,我正在寻找解决这个问题的方法。第一个解决方案是使用 POST 而不是 GET。这行得通,但是将 DRF 与数据表集成的库没有处理 POST 请求的表单参数。因此,过滤、分页等功能已停止工作。

解决这个问题最简单的方法是将表单参数放入查询参数中,让后端处理请求,就像它是一个普通的 GET 请求一样。

这就是我目前正在做的事情:

class DataViewSet(viewsets.ModelViewSet):

    queryset = Data.objects.all()
    serializer_class = DataSerializer

    def create(self, request, *args, **kwargs):
        # DataTable uses a lot of parameters which do not fit into a normal URL. To get the data we need to do POST,
        #   so that the parameters are sent in the body
        # We hijack the create method to list the data
        return self.list(request, *args, **kwargs)
4

1 回答 1

0

我不知道有任何公认的方法。但是让我给你一个想法。它可能与接受的含义相反。

rest_framework.request.Request.query_params看起来像这样:

@property
def query_params(self):
    return self._request.GET

我正在考虑self._request.GETself._request.POST

class DataViewSet(viewsets.ModelViewSet):

    queryset = Data.objects.all()
    serializer_class = DataSerializer

    def create(self, request, *args, **kwargs):
        # DataTable uses a lot of parameters which do not fit into a normal URL. To get the data we need to do POST,
        #   so that the parameters are sent in the body
        # We hijack the create method to list the data
        request._request.GET = request._request.POST
        return self.list(request, *args, **kwargs)

应该适用于POST数据。将文件发送到此端点可能是个坏主意。

注意:这很可疑,将来可能会引入错误。如果不查看您的代码,我无法预测副作用。

于 2018-10-11T16:27:24.837 回答