在django rest中不处理URL查询参数

时间:2016-10-17 19:26:36

标签: python django django-views django-rest-framework

这是我的views.py

class my4appCompanyData(generics.ListAPIView):
    serializer_class = my4appSerializer

    def get_queryset(self,request):
        """Optionally restricts the returned data to ofa company,
        by filtering against a `id` query parameter in the URL. """
        queryset = companies_csrhub.objects.all()
        #url_id = self.request.query_params.get('id', None)
        url_id = request.GET.get('id', None)
        if id is not None:
            queryset = queryset.filter(id=url_id)
        elif id is ALL:
            queryset = companies_csrhub.objects.all()
        else:
            queryset = "Error data not found"
        return queryset

我的urls.py

router.register(r'api/my4app/company/$', views.my4appCompanyData.as_view(),base_name="company")

用于检查的网址:mywebsite/api/my4app/company/?id=100227

计划添加具有默认值但不起作用的多个过滤器。请帮忙。

2 个答案:

答案 0 :(得分:0)

class my4appCompanyData(generics.ListAPIView):
    serializer_class = my4appSerializer

    def get_queryset(self,request):
        """Optionally restricts the returned data to ofa company,
        by filtering against a `id` query parameter in the URL. """
        queryset = companies_csrhub.objects.all()
        url_id = request.query_params.get('id', None)
        if id is not None:
            queryset = queryset.filter(id=url_id)
        elif id is ALL:
            queryset = companies_csrhub.objects.all()
        else:
            queryset = []
        return queryset

删除返回ID,因为id不是查询集,因此它会给出错误。同样在if语句的else部分,你返回字符串,但你也不能这样做,因为字符串不是一个查询集。

答案 1 :(得分:0)

根据官方文件(http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters

我认为您的代码无效,因为您正在使用:

url_id = request.query_params.get('id', None)

而不是:

url_id = self.request.query_params.get('id', None)

在文档中,您可以发现get_queryset函数只接收self参数,您必须删除request参数。