首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从Django Rest框架和数据表获取请求参数时出错

从Django Rest框架和数据表获取请求参数时出错
EN

Stack Overflow用户
提问于 2018-07-13 08:34:27
回答 1查看 286关注 0票数 0

我正在尝试使用DRF和Datatables来填充一个包含大量数据的表,并进行服务器端处理。

下面是我的观点:

class ProductsListAPIView(LoginRequiredMixin, ListAPIView):
    authentication_classes = (authentication.SessionAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = ProductSerializer

    def get_queryset(self):
        qs = Product.objects.filter(user=self.request.user).order_by("-timestamp")
        return qs

    def list(self, request, *args, **kwargs):
        draw = int(self.request.GET["draw"])
        start = int(self.request.GET["start"])
        length = int(self.request.GET["length"])

        queryset = self.get_queryset()
        queryset = queryset[start:start+length]
        serializer = ProductSerializer(queryset, many=True)
        result = {"draw": draw,
                  "recordsTotal": queryset.count(),
                  "recordsFiltered":queryset.count(),
                  "data": serializer.data}
        return Response(result)

下面是Datatables和Ajax的脚本:

$(document).ready(function() {
     $('#exampleAjax2').dataTable( {
         "autoWidth": true,
         "displayLength": 10,
         "lengthChange": false,
         "ordering": false,
         "processing": true,
         "searching": false,
         "serverSide": true,
         "language": {
            "zeroRecords": "Nothing to display",
            "info": "Showing _START_ to _END_ of _TOTAL_ records",
            "infoEmpty": ""
        },
         "ajax": {
             "processing": true,
             "url": "/my-products/",
             "dataSrc": ""
         },
       "columns": [....],
     });
 });

我得到以下错误:KeyError: 'draw'

这可能意味着我没有使用正确的方法来获取参数。虽然这是我第一次尝试使用DRF和Datatables进行服务器端处理,但也可能存在其他错误。

EN

回答 1

Stack Overflow用户

发布于 2018-07-13 09:31:25

它应该是:

"url": "/my-products/?draw=0&start=0&length=0"

在Ajax和:

draw = int(self.request.GET.get("draw", 0))
start = int(self.request.GET.get("start", 0))
length = int(self.request.GET.get("length", 0))

在DRF中

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51316201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档